How to measure Performance by using High Resolution Timer in Visual C++?
![]()
Ever had a performance tweaking project? The first thing you need is a high resolution stop watch to measure performance of different code blocks. But is there a high resolution stop watch?

![]()
You can use QueryPerformanceCounter(). You can get the performance counter frequency – i.e. ticks per second by calling QueryPerformanceFrequency(). Have a look at the sample CStopWatch class.
// Stop watch class.
class CStopWatch
{
public:
// Constructor.
CStopWatch()
{
// Ticks per second.
QueryPerformanceFrequency( &liPerfFreq );
}
// Start counter.
void Start()
{
liStart.QuadPart = 0;
QueryPerformanceCounter( &liStart );
}
// Stop counter.
void Stop()
{
liEnd.QuadPart = 0;
QueryPerformanceCounter( &liEnd );
}
// Get duration.
long double GetDuration()
{
return ( liEnd.QuadPart - liStart.QuadPart) /
long double( liPerfFreq.QuadPart );
}
private:
LARGE_INTEGER liStart;
LARGE_INTEGER liEnd;
LARGE_INTEGER liPerfFreq;
};
int main()
{
// Stop watch object.
CStopWatch timer;
// Start timer.
timer.Start();
// ZZzzzzz... for few seconds.
Sleep( 3000 );
timer.Stop();
// Get the duration. Duration is in seconds.
long double duration = timer.GetDuration();
return 0;
}
![]()
Even if the sample app slept for 3 seconds, in high resolution timer, the duration is 2.9xxx seconds.
Can you guess why?
![]()
Targeted Audiance – Intermediate.
You can use GetTickCount() for high resolution timers.
Hello marko,
GetTickCount() returns elapsed time in milliseconds. And if you need more accurate timing, then use – QueryPerformanceCounter().
Thanks for the comments and keep watching…
Regards,
Jijo.
My guess is it can’t stop at exactly 3 seconds because the CPU clock cycle couldn’t land exactly on 3 seconds, but it landed close. The clock cycle is based on the processor speed (1hz = 1second) and its a fixed time. There are so many clock cycles that you would think it could land on 3sec, but then you have to keep in mind the superscalar architecture and the pipeline, and if it was even possible to land on 3 sec. So many factors.