【问题标题】:clock() returning negative time difference on Windows machine时钟()在 Windows 机器上返回负时差
【发布时间】: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。

  1. 谁能解释一下为什么end 的值小于begin
  2. 如何在 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。跨度>

标签: c windows


【解决方案1】:

在 Windows 7 中,有一系列可用的时钟和间隔计时器,包括物理和通过接口。究竟是哪个cpu(s)???某些时间/定时器功能会出现倒退!!!至少对于短时间间隔/分辨率。这是一个众所周知的问题。请参阅 Mircosoft 网络资料。猜测一下,您可能想要 win32 API 间隔计时器。

【讨论】:

    猜你喜欢
    • 2012-01-26
    • 2013-10-22
    • 2014-05-17
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    相关资源
    最近更新 更多