Associated Files: PerfTimer.zip
This timer was developed with the aim of using it to time sections of code, within a Windows application, during the debug/testing phases of development. Although commercial tools can be used for this purpose, it is often simpler to drop in a couple of lines of code just to test a particular section of the application.
The limitations of the Windows 'GetTickCount' function are well known and, as a result, the use of this function is inappropriate for any sort of serious time measurements. As an alternative, the 'QueryPerformanceCounter' function is commonly used, providing microsecond resolution and low latency. The performance timer described in this article makes full use of this function during operation.
The performance timer class is very simple - it has functions to start, stop and reset the timer. There are three functions which allow the timer to be queried for the elapsed time in microseconds, milliseconds or seconds. There are also three functions which return the timer's resolution, again in microseconds, milliseconds and seconds. The remaining member function returns the calculated correction, which is applied to the elapsed time value, to take into account the start and stop function call overhead.
To use the timer in your code, simply declare a new timer object in the usual manner. Then, place a timer start call immediately before the function or code block you wish to time. Place the timer stop function call immediately after the code block or function call, then call the desired timer function to retrieve the elapsed time in microseconds, milliseconds or seconds.
When a new timer object is declared, the constructor calls an internal timer initialisation function. This function performs a simple 'benchmark' of the timer start and stop functions to determine the overhead involved in calling these functions. The calculated correction is subtracted from any subsequent elapsed time value the timer measures. This correction is re-calculated whenever the timer is reset.
Note, on modern dual core computers, you should specify the CPU on which all the threads of your process will run, before using this timer. This can be done by calling 'SetProcessAffinityMask'. If this is not done, the performance of the timer may vary depending on the core allocated by the operating system. The performance timer source code can be downloaded via the ayrware downloads page.