实时与 cpu 时间性能指标
real time vs. cpu time performance measure
我正在尝试通过测量以毫秒为单位的实际经过时间与以毫秒为单位的 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 时间的概念?
简而言之:
- real-time: 墙上的普通时钟测量的时间
- cpu-time: CPU(s) was/were 忙的总时间
如果你有多个 cpu 那么他们的时间加起来,例如在 1 秒 real-time 你可以使用 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。
我正在尝试通过测量以毫秒为单位的实际经过时间与以毫秒为单位的 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 时间的概念?
简而言之:
- real-time: 墙上的普通时钟测量的时间
- cpu-time: CPU(s) was/were 忙的总时间
如果你有多个 cpu 那么他们的时间加起来,例如在 1 秒 real-time 你可以使用 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。