gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:20:05 25 4
gpt4 key购买 nike

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

现在,我这样测量时间:

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是完全一样的...

我用 watch 测量了时间,结果是挂钟时间。因此,clock() 显然没有显示 CPU 时间,如果 8 个 CPU 100% 并行工作,CPU 时间应该高得多。 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)

关于c++ - `clock()` 给出通常的时钟而不是 CPU 时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54219450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com