【发布时间】:2020-11-26 21:34:00
【问题描述】:
我用 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 机器上解决此问题。
(clock() returning a negative value in C 仅谈论 POSIX)。
【问题讨论】:
-
@Blindy 这个解决方案讲的是POSIX,在windows机器上会不会有所不同?如果我错了,请纠正我,但 clock() 在 Windows 和 UNIX 上的行为不同。
-
如果您正在寻找仅适用于 Windows 的解决方案,您有
QueryPerformanceCounter。您提到了 [c],但是如果您也可以访问 C++,那么可移植的等价物是标准的chrono库,它在 Windows 内部使用 QPC.. -
我在看到 Windows 7 的重点之前投票关闭(在我投票期间编辑。)。链接的副本特定于 Linux,并没有解决这个问题。正在投票重新开放。
-
clock()环绕(就像一个真正的时钟),因此过去的时间可以比现在具有更大的价值(与凌晨 2 点之前的 4 小时是晚上 10 点相同:2 - 10 = -8/2 - 22 = -20) -
@pmg 假设 OP 使用(使用)Windows UCRT 的编译器,
clock()不会环绕,而是 returns-1在 25 天左右后达到LONG_MAX。跨度>