Timers are useful to find the performance bottlenecks in code. If a timer resolution of 1ms is enough for your application, you can use the clock
function from <ctime>
as shown here.
However, if you need timers of a far higher resolution on Windows, a popular choice is to use the high-resolution performance counter API. All calls of this API rely on a LARGE_INTEGER
data type.
Use QueryPerformanceCounter to note down the begin and end times of your code:
#include <windows.h> LARGE_INTEGER beginTime; QueryPerformanceCounter( &beginTime ); // Code to measure ... LARGE_INTEGER endTime; QueryPerformanceCounter( &endTime );
Use QueryPerformanceFrequency to find the timer frequency. Use that to convert the time difference to seconds:
LARGE_INTEGER timerFreq; QueryPerformanceFrequency( &timerFreq ); const double freq = 1.0f / timerFreq.QuadPart; const double timeSeconds = ( endTime.QuadPart - beginTime.QuadPart ) * freq;
A PerfTimer class that exposes this as simple start()
, stop()
and value()
calls is available here.
Tried with: Visual C++ 2008
Btw, maximum Windows timer resolution is 10 or 15 milliseconds (depending of the underlying hardware).
Current PerfTimer implementation can work incorrectly on some multi-core CPU-s.
Better algorithm described here http://msdn.microsoft.com/en-us/library/ee417693(VS.85).aspx
LikeLike
airmax: Thanks for pointing out that this might affect performance of multi-threaded applications running on certain multi-core CPUs.
LikeLike