我一直在尝试使用时钟函数测量C程序中经过的时间,但每当我尝试printf任何时钟值时,我都会回来0.例如:
clock_t time1, time2;
time1 = clock();
printf("Time 1 is %d.\n", (int)time1);
sleep(2);
time2 = clock();
printf("Time 2 is %d.\n", (int)time2);
在这两种情况下,time1和time2打印为0.我有一种感觉,因为我在printf中使用了错误的类型,但我看到的每种类型似乎都不适合我 . 我使用%Lf,%ld,%f . 其他人可以在这里发现问题吗?
编辑:我尝试了这个线程中提到的大多数类型:What’s the correct way to use printf to print a clock_t?我甚至尝试了uintmax_t,但没有打印p1和p2的能力,我没有't know how to verify if it' s类型问题或者如果时钟没有返回足够的值 .
1 回答
来自cplusplus.com
基本上,如果您的计算时间太短,您将不会注意到任何事情 .
尝试添加一个从0到大的while循环并在其中增加一个volatile变量,然后再次调用
clock()
.