c - 奇怪的时钟()行为

标签 c time clock

有人可以解释一下这个时钟()(time_h)行为吗:

clock_t start, stop;
long i;
double t = 0.;
for(i = 0; i < 10e7; i++){
    start = clock();
    //nothing
    stop = clock();
    t = t + (double)(stop - start) / CLOCKS_PER_SEC;
}
printf("t: %fs\n", t);

输出:

t: 12.883712s

我认为原因可能是由clock()错误引起的小t值的累积。有办法解决吗?

更新:只是为了解释“现实世界”的情况,因为有很多建议。 //nothing 是一段代码,其时间间隔非常小(可能是纳米级),而不是一个循环,其中很少有也难以测量。

最佳答案

您得到的答案是合理的,因为编译器无法优化 clock() 调用,并且我没有看到对 clock() 的调用因为特别便宜。

但是你的测量在数字上不准确 - 我认为你的方法低估了总数。尝试一下

clock_t start, stop;
clock_t total = 0;
for (long/*don't overflow a 16 bit int*/ i = 0; i < 10e7; i++){
    start = clock();
    stop = clock();
    total += stop - start
}
double t = 1.0 * total / CLOCKS_PER_SEC;
printf("t: %fs\n", t);

相反。即最后进行除法。

从某种意义上说,您可以使用校准开销

start = clock();
/*ToDo - the real code*/
stop = clock();
control = clock();
/*Time is (stop - start) - (control - stop)*/

关于c - 奇怪的时钟()行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37858708/

相关文章:

PHP如何查找自日期时间以来耗时?

jquery - 使用jquery输入时间掩码

synchronization - Windows Azure 上的时钟同步质量如何?

c - 将两个指针字符串连接在一起的函数

c++ - 从 Python 调用 C/C++?

c - 在函数声明中收到错误

JavaScript 日期时区奇怪的行为

c++ - 在 SFML 中,时钟有限制吗?

java - 无法获得 Gui Java Clock 的正确点

c++ - 在沙盒中运行插件