C`clock()`函数只返回零

C clock()函数只返回零。 我尝试使用不同的类型,没有任何改进……这是一个很好的精确测量时间的方法吗?

 #include  #include  int main() { clock_t start, end; double cpu_time_used; char s[32]; start = clock(); printf("\nSleeping 3 seconds...\n\n"); sleep(3); end = clock(); cpu_time_used = ((double)(end - start)) / ((double)CLOCKS_PER_SEC); printf("start = %.20f\nend = %.20f\n", start, end); printf("delta = %.20f\n", ((double) (end - start))); printf("cpu_time_used = %.15f\n", cpu_time_used); printf("CLOCKS_PER_SEC = %i\n\n", CLOCKS_PER_SEC); return 0; } 
 Sleeping 3 seconds... start = 0.00000000000000000000 end = 0.00000000000000000000 delta = 0.00000000000000000000 cpu_time_used = 0.000000000000000 CLOCKS_PER_SEC = 1000000 

平台:Intel 32位,RedHat Linux,gcc 3.4.6

clock()报告使用的CPU时间。 sleep()不使用任何CPU时间。 所以你的结果可能完全正确,只是不是你想要的。

man clock 。 它没有回归你的想法。 也是man gettimeofday它更可能是你想要的。

clock_t是整数类型。 您无法使用%f打印出来。 请参阅弗雷德的答案,了解为什么差异为0。

  printf("start = %.20f\nend = %.20f\n", start, end); 

应该:

  printf("start = %d\nend = %d\n", start, end); 

调用sleep()不会占用任何CPU时间。 不过,你应该看到一点点不同。 我纠正了这行中的printf类型不匹配错误:

 printf("start = %.20f\nend = %.20f\n", start, end); 

它在我的机器上给出了合理的结果:

 start = 1419 end = 1485 delta = 66 cpu_time_used = 0.000066000000000 CLOCKS_PER_SEC = 1000000 

您可以尝试使用gettimeofday()来获得运行程序所花费的实际时间。

你可能需要

double get_wall_time(){ struct timeval time; if (gettimeofday(&time,NULL)){ return 0; } return (double)time.tv_sec + (double)time.tv_usec * .000001; } 和使用类似的东西

double wall0 = get_wall_time(); double cpu0 = get_cpu_time(); for(long int i = 0; i<=10000000;i++){ func1(); } double wall1 = get_wall_time(); double cpu1 = get_cpu_time(); cout << "Wall Time = " << wall1 - wall0 << endl; cout << "CPU Time = " << cpu1 - cpu0 << endl;

而不是clock()

仅作为时钟,仅根据性能计数器计算在CPU中花费的时间。 但你可以通过使用上面的function得到结果。 只是为了validation您的应用程序使用time命令运行它

喜欢time ./a.out

输出时间命令:

real 0m5.987s user 0m0.674s sys 0m0.134s

和自定义function的输出Wall Time = 5.98505 CPU Time = 0.8