If I had the following code
clock_t t;
t = clock();
//algorithm
t = clock() - t;
t would equal the number of ticks to run the program. Is this the same is CPU time? Are there any other ways to measure CPU time in C++?
OS -- Debian GNU/Linux I am open to anything that will work. I am wanting to compare the CPU time of two algorithms.
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";
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).
来源:https://stackoverflow.com/questions/20167685/measuring-cpu-time-in-c