Search This Blog

Thursday, June 4, 2009

High Resolution Performance Counter - Win32 VC++

Intro.


Sometimes, you need to monitor the performance of a block of your program.. or a loop execution time.. or a function performance in terms of execution time..

There is an API GetCurrentTime() which you may go for, and eveluate the difference between two calls.. But, this method is very less accurate... so, you wont get the needed result accurately..


There are other functions like GetTickCount() but, unfortunately this one also cannot provide you sharp and accurate results...


Now, what to do?? :(

Solution.


For every problem, there is a solution :) here,  Windows API named QueryPerformanceFrequency() and QueryPerformanceCounter() can help us overcome the situation!


Giving Documentation isnt 'My Cup of Tea' and, for thats what MSDN is meant for.. :)


So, better read MSDN Documentation of these API's and proceed...

Code.


Here, i'm giving a Function.. which returns the time elapsed from the last call... First call will always return a value Zero... This uses the High Resolution performance counter. If it does not exist, each call returns zero..



float GetTimeDifference()
{
  // Last counter reading, initializing with zeroes
  static LARGE_INTEGER OldCounter = {0, 0};


  LARGE_INTEGER Counter, Frequency;
  if (QueryPerformanceFrequency(&Frequency))
  {
    // Gets current counter reading
    QueryPerformanceCounter(&Counter);


    // Calculates time difference (zero if called for the first time)
    float TimeDiff = OldCounter.LowPart ? (float) (Counter.LowPart - OldCounter.LowPart) / Frequency.LowPart;


    // Resets last counter reading, and stores value of current to old counter
    OldCounter = Counter;


    // Returns time difference in unit of Seconds
    return TimeDiff;
  }
  else
  {
    // No high resolution performance counter; function returns zero
    return 0;
  }
}

PS : The accuracy is determined by the high-resolution performance counter frequency.

Your valuable comments expected. Please help me to improve :-)

No comments:

Post a Comment