Measuring CPU time in c++

偶尔善良 提交于 2019-12-01 16:52:35

clock() is specified to measure CPU time however not all implementations do this. In particular Microsoft's implementation in VS does not count additional time when multiple threads are running, or count less time when the program's threads are sleeping/waiting.

Also note that clock() should measure the CPU time used by the entire program, so while CPU time used by multiple threads in //algorithm will be measured, other threads that are not part of //algorithm also get counted.

clock() is the only method specified in the standard to measure CPU time, however there are certainly other, platform specific, methods for measuring CPU time.

std::chrono does not include any clock for measuring CPU time. It only has a clock synchronized to the system time, a clock that advances at a steady rate with respect to real time, and a clock that is 'high resolution' but which does not necessarily measure CPU time.

How to mesure cpu-time used ?

#include <ctime>

std::clock_t c_start = std::clock();
// your_algorithm
std::clock_t c_end = std::clock();

long_double time_elapsed_ms = 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC;
std::cout << "CPU time used: " << time_elapsed_ms << " ms\n";

Of course, if you display time in seconds :

std::cout << "CPU time used: " << time_elapsed_ms / 1000.0 << " s\n";

Source : http://en.cppreference.com/w/cpp/chrono/c/clock

C++ has a chrono library. See http://en.cppreference.com/w/cpp/chrono. There are also often platform dependent ways to get at high resolution timers (obviously varies by platform).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!