【问题标题】:How to get the time elapsed running a function in C++如何获取在 C++ 中运行函数的时间
【发布时间】:2011-03-12 14:17:51
【问题描述】:

我通过谷歌搜索尝试了一些代码:

clock_t start, end;
start = clock();
//CODES GOES HERE
end = clock();
std::cout << end - start <<"\n";
std::cout << (double) (end-start)/ CLOCKS_PER_SEC;

但结果经过时间始终为 0,即使使用

std::cout << (double) (end-start)/ (CLOCKS_PER_SEC/1000.0 );

不知道为什么,但是当我在 Java 中得到类似的结果时:getCurrentTimeMillis() 它运行良好。我希望它显示毫秒,因为计算机的计算速度可能如此之快。

【问题讨论】:

  • 任何操作系统/框架限制? (C++ 没有获得高分辨率计时的标准方法......)

标签: c++ elapsedtime


【解决方案1】:

我认为不能保证clock 具有足够高的分辨率来分析您的函数。如果你想知道一个函数的执行速度有多快,你应该运行它几千次而不是一次,测量它所花费的总时间并取平均值。

【讨论】:

    【解决方案2】:
    #include <boost/progress.hpp>
    
    int main()
    {
        boost::progress_timer timer;
        // code to time goes here
    }
    

    这将打印出运行 main 所花费的时间。您可以将您的代码放在作用域中以对多个部分进行计时,即{ boost::progress_timer timer; ... }

    【讨论】:

    • 编译器无法识别 。我在 Ubuntu 中使用 Netbeans
    • 嗯,你需要 Boost。试试sudo apt-get install boost-dev 或类似的东西。
    【解决方案3】:

    这个问题和你的有点相似:Timing a function in a C++ program that runs on Linux

    看看this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多