How to measure Performance by using High Resolution Timer in Visual C++?

31 03 2009


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?

highperformancetimer


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.

Advertisements