题
的C clock()
函数只是返回我一个零。我试着用不同的类型,有没有改善?这是一个很好的方法来衡量,用良好的精度?
#include <time.h>
#include <stdio.h>
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
平台:英特尔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花费仅基于性能计数器。 但你可以通过使用上述功能得到结果。 只是为了验证你的应用程序与时间命令运行
像time ./a.out
时间命令的输出:
real 0m5.987s
user 0m0.674s
sys 0m0.134s
和自定义函数的输出
Wall Time = 5.98505
CPU Time = 0.8