gpt4 book ai didi

c++ - 实时与 CPU 时间性能测量

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

我正在尝试通过测量以毫秒为单位的实际运行时间与以毫秒为单位的 CPU 时间来用 C++ 进行一些性能测量。这是我的代码的样子:

auto start = std::chrono::high_resolution_clock::now();
unsigned begin = clock();

// some computationally expensive task

auto finish = std::chrono::high_resolution_clock::now();
unsigned end = clock();

(finish - start).count();

int duration = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count();
int cpu_duration = 1000*(end - begin)/(CLOCKS_PER_SEC);

现在我希望 cpu 时间值低于系统时间,因为线程可能会被中断。但是cpu时间比实际时间高2-3倍。我是做错了什么还是误解了 CPU 时间的概念?

最佳答案

简而言之:

  • 实时:使用墙上的普通时钟测量的时间
  • cpu-time:CPU 忙碌的总时间

如果您有多个 CPU,那么它们的时间加起来,例如,在 1 秒的实时时间中,您可以使用 4 秒的 CPU 时间。

cppreference 关于 std::clock 的文档明确区分挂钟和 CPU 时间:

[...]if the CPU is shared by other processes, std::clock time may advance slower than wall clock. On the other hand, if the current process is multithreaded and more than one execution core is available, std::clock time may advance faster than wall clock.

有关更多详细信息,请参见例如 here .

关于c++ - 实时与 CPU 时间性能测量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56445158/

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