`clock()` 给出通常的时钟而不是 CPU 时钟

`clock()` gives usual clocks instead of CPU clocks

我曾经用 clock() 来获得我的算法的 CPU 时间。但是,它似乎不再起作用了。我有一个 Windows 10 VM,有 8 个 CPUs,在资源监视器中也可以看到。

现在,我这样测量时间:

auto startTime = std::chrono::high_resolution_clock::now();
auto startClocks = std::clock();

// some code with TBB that uses multiple threads

auto endTime = std::chrono::high_resolution_clock::now();
auto endClocks = std::clock();
auto duration = endTime - startTime;
auto clockDuration = endClocks - startClocks;

auto durationSeconds = static_cast<double>(std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()) / 1000.;
auto durationCpuSeconds = 1. * clockDuration / CLOCKS_PER_SEC;

TBB 部分确实有效,正如我在 Windows 的资源监视器中看到的那样,所有 CPU 都以 100% 的速度工作。如果我在没有并行化的情况下开始无限循环,CPU 使用率仅为预期的 12.5%。

然而,durationSecondsdurationCpuSeconds完全一样...

我用手表测了时间,结果是挂钟时间。因此,clock() 显然没有显示 CPU 时间,而 8 CPU 秒 100% 并行工作时,该时间应该明显更长。 clock() 是不可靠还是我遗漏了什么?

是的,它在 Windows 上坏了。

The clock function tells how much wall-clock time has passed since the CRT initialization during process start. Note that this function does not strictly conform to ISO C, which specifies net CPU time as the return value. To obtain CPU times, use the Win32 GetProcessTimes function.

(来自 Microsoft's clock docs