I would like to know how to best measure the execution time of a C ++ program. I found several solutions on the internet, each with an approach. Suggestions?
I would like to know how to best measure the execution time of a C ++ program. I found several solutions on the internet, each with an approach. Suggestions?
For Windows specifically, the best way (in the sense of having higher resolution) is to use the
QueryPerformanceCounter
.
An example use (use a recent compiler):
#include <windows.h>
#include <iostream>
#include <cstdint>
class Watch
{
public:
Watch()
{
LARGE_INTEGER li;
if(!QueryPerformanceFrequency(&li))
{
std::cout << "QueryPerformanceFrequency failed!\n";
return;
}
mPCFreq = static_cast<double>(li.QuadPart)/1000.0;
QueryPerformanceCounter(&li);
mCounterStart = li.QuadPart;
}
// Retorna o tempo em milisegundos desde que o
// objeto Watch foi criado.
double getCounter()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return static_cast<double>(li.QuadPart - mCounterStart)/mPCFreq;
}
private:
uint64_t mCounterStart;
double mPCFreq;
};
int main()
{
Watch counter;
Sleep(1000);
std::cout << counter.getCounter() << std::endl;
return 0;
}
In this case, the code returns the time in milliseconds between the creation of object Watch
and call counter.getCounter()
.
Another more portable solution is to use the boost library and use boost::posix_time::time_duration
to measure the time in the scale you want (milliseconds, microseconds, seconds).
C ++ 11 provides high_resolution_clock , it is the ideal solution but Microsoft does not yet provide an implementation that uses QueryPerformanceCounter. This is considered a bug , and it looks like it will be resolved in the next version of visual studio. So at the moment you'd better use QueryPerformanceCounter directly or a library whose implementation you use .
The text ( Optimizing software in C++
- recommend reading) shows how we can achieve this.
Translated:
Time measurements may require a very high resolution if the time intervals are short. In Windows, you can use the functions
GetTickCount
orQueryPerformanceCounter
for millisecond resolution. The much higher resolution can be obtained with the time stamp counter on the CPU, which counts the clock frequency of the CPU.
There is a problem that the clock frequency can vary dynamically and that the measurements are unstable due to interrupts and switches .
It's also interesting to look at the StopWatch
class % file that is based on two API's , the QueryPerformanceFrequency
" and QueryPerformanceCounter
.