【问题标题】:Different values in measuring the elapsed time C++测量经过时间的不同值 C++
【发布时间】:2014-11-22 11:15:15
【问题描述】:

我有一个简单的代码,我使用 clock() 和其他建议的方法来测量程序的运行时间。问题是当我多次运行它时我得到了不同的值。 有什么办法可以超过程序的实际执行时间?

提前致谢

【问题讨论】:

    标签: c++


    【解决方案1】:

    它使用#include <ctime>的一种方式

    clock_t t = clock();       //  take a start time 
    // ... do something 
    clock_t dt = clock() - t;  // take elapsed time 
    cout << (((double)dt) / CLOCKS_PER_SEC) * 1000);  // duration in MILLIseconds.  
    

    另一种方法使用high_resolution_clock#include &lt;chrono&gt;

      chrono::high_resolution_clock::time_point t = chrono::high_resolution_clock::now();
      //... do something
      chrono::high_resolution_clock::time_point t2 = chrono::high_resolution_clock::now();
      cout << chrono::duration_cast<chrono::duration<double>>(t2 - t).count();
      // or if you prefer duration_cast<milliseconds>(t2 - t).count();
    

    在任何情况下,发现细微的变化都是正常的。第一个原因是您在 PC 上运行的其他程序。第二个原因是时钟精度(例如著名的 windows 上的 15 毫秒)。

    【讨论】:

    • 比你,我认为你提到的第一种方式会在毫秒内产生。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2021-05-25
    • 2013-01-18
    • 1970-01-01
    相关资源
    最近更新 更多