高分辨率时序部分代码

时间:2009-03-31 07:22:35

标签: c++ time high-resolution

我想测量循环中函数的速度。但是为什么我这样做的方式总是打印“0”而不是9位十进制精度的高分辨率时序(即以纳秒/微秒为单位)?

这样做的正确方法是什么?

#include <iomanip>
#include <iostream>
#include <time.h>
int main() {


 for (int i = 0; i <100; i++) {
    std::clock_t startTime = std::clock(); 
    // a very fast function in the middle
    cout << "Time: " << setprecision(9) << (clock() - startTime + 0.00)/CLOCKS_PER_SEC << endl;
 }

 return 0;
}

相关问题:

6 个答案:

答案 0 :(得分:6)

将时间计算函数移到for () { .. }语句之外,然后将总执行时间除以测试循环中的操作数。

#include <iostream>
#include <ctime>
#define NUMBER 10000 // the number of operations

// get the difference between start and end time and devide by
// the number of operations
double diffclock(clock_t clock1, clock_t clock2)
{
    double diffticks = clock1 - clock2;
    double diffms = (diffticks) / (CLOCKS_PER_SEC / NUMBER);
    return diffms;
}

int main() {
    // start a timer here
    clock_t begin = clock();

    // execute your functions several times (at least 10'000)
    for (int i = 0; i < NUMBER; i++) {
        // a very fast function in the middle
        func()
    }

    // stop timer here
    clock_t end = clock();

    // display results here
    cout << "Execution time: " << diffclock(end, begin) << " ms." << endl;
    return 0;
}

注意:std :: clock()缺乏足够的分析精度。 Reference

答案 1 :(得分:3)

一些指示:

  1. 我会小心优化器,如果我认为它没有做任何事情,它可能会抛出你的所有代码。
  2. 您可能希望循环运行100000次。
  3. 在执行总时间calc之前,将当前时间存储在变量中。
  4. 多次运行您的程序。

答案 2 :(得分:3)

如果您需要更高的分辨率,唯一的方法是依赖平台。

在Windows上,查看QueryPerformanceCounter/QueryPerformanceFrequency API。

在Linux上,查找clock_gettime()

答案 3 :(得分:2)

看到我问过同一件事的问题:显然clock()的分辨率不能保证这么高。

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

尝试使用gettimeofday功能,或boost

答案 4 :(得分:2)

如果您需要平台独立性,您需要使用类似ACE_High_Res_Timer(http://www.dre.vanderbilt.edu/Doxygen/5.6.8/html/ace/a00244.html

的内容

答案 5 :(得分:1)

您可能希望了解如何使用openMp。

#include <omp.h>

int main(int argc, char* argv[])
{       
    double start = omp_get_wtime();

    // code to be checked

    double end = omp_get_wtime();

    double result = end - start;

    return 0;
}