我用C语言编写了以下程序,用于计算(在Windows-7机器上)的执行时间:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
double time_spent = 0.0;
clock_t begin;
clock_t end;
begin = clock();
// code to read a file
end = clock();
time_spent += ((double)(end - begin)) / CLOCKS_PER_SEC;
printf("Time elapsed is %f seconds", time_spent);
getch();
return 0;
}
执行结束时,(end-begin)
的值为负数。此外,程序执行后,begin
的值为46,而end
的值为43。
我正在使用64位Windows 7。
- 请问有人能解释一下为什么
end
的值比begin
小吗? - 如何在Windows机器上解决这个问题?
QueryPerformanceCounter
。您提到了[c],但是如果您也可以访问C ++,则便携式等效库是标准的chrono
库,它在Windows中内部使用QPC。 - Blindyclock()
回绕 (就像真实的时钟一样),因此过去的时间可能具有比现在更大的值 (与凌晨2点前4小时相同,是晚上10点:2 - 10 = -8
/2 - 22 = -20
)。 - pmgclock()
也使用了QPC。 - dxiv