有人可以解释一下这个时钟()(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/