【发布时间】:2014-03-11 01:27:33
【问题描述】:
我试图获取特定代码段(可能是循环或函数等)的执行时间。我听说命令time 或函数clock() 可以完成这项工作。但我的要求是以毫秒/微秒为单位的精度。所以我写了这样的东西。
int main()
{
struct timeval ts1, ts2;
long long time1, time2, diff;
int i,var;
scanf("%d",&var);
gettimeofday(&ts1, NULL);
time1 = (ts1.tv_sec * 1000000) + ts1.tv_usec;
for (i=0; i<var; i++); // <-- Trying to measure execution time for the loop
gettimeofday(&ts2, NULL);
time2 = (ts2.tv_sec * 1000000) + ts2.tv_usec;
printf("-------------------------\n");
diff = time2 - time1;
printf("total %ld microseconds\n", diff);
printf("%ld seconds\n", diff/1000000);
diff %= 1000000;
printf("%ld milliseconds\n", diff/1000);
diff %= 1000;
printf("%ld microseconds\n", diff);
printf("-------------------------\n");
return 0;
}
我有两个顾虑
- 上面的代码是否可靠,是否符合我的意图?我不太确定;)
- 当我编译优化级别为 -O2 的代码时,这根本不起作用。我知道 -O2 会化妆,但我怎么看发生了什么?如果我可以选择 1,谁能建议如何恢复 O2 问题?
感谢您的帮助!谢谢。
【问题讨论】:
-
你是想计算一些代码行之间的时间差,还是获取真正的 CPU 执行时间?
-
使用
clock_gettime。另见here。记得链接-lrt。 -
优化器可能正在移除循环,因为从未使用过
i。检查生成的汇编代码。 -
我正在尝试获取某些代码行的实时运行时间。这就是我在这里尝试的。甚至认为我也对 CPU 执行时间感兴趣..
-
您需要小心减去那些包含两个分量的时间结构。我在下面的回答中给出了
clock_gettime()使用的timespec结构的示例,如果您想继续使用它们,可以适应timevals。我最初改编自 a GNU example fortimevalstructs 的版本。
标签: c++ c linux performance