Loading

Miscellaneous C++: A High-Resolution Timer

A High-Resolution Timer

In this video lesson, we create a timer class, which we will be able to use to time sections of code for optimization and for creating real-time games. The project that we created is a simple console project like the one we made in C++ Console
Lesson 1.

Our timer class makes use of two Windows-specific functions: QueryPerformanceFrequency() and QueryPerformanceCounter(). To use these Windows functions, we need to include the "windows.h" file. These functions can be used to get counts per second and the current count for the internal counter. To time a section of code, we get the count at the beginning and the count at the end. Then we subtract the count at the beginning from the count at the end and divide by the frequency:

Our Timer class encapsulates this functionality in a few functions. The Start() and End() functions are called to get the counts before and after the timed code that is executed, respectively. Once we have the start and end counts, it is trivial to calculate the elapse time by using the frequency and formula above. The elapse time is calculated in seconds when we call GetTimeInSeconds(). Alternatively, we can call one of the other three functions to calculate the elapsed time milliseconds, microseconds, or nanoseconds. The class has provides three variables for the start count, end count, and frequency. The full class definition is shown below:

The type LARGE_INTEGER that is used here can be thought of as a 64-bit integer. In fact, the member "QuadPart" is a long long type, which is a 64-bit integer as we showed in our Console Lesson 24. In the video, we showed how to time a sorting function. However, we can use this to time anything, by using this format:

CTimer qMyTimer;
qMyTimer.Start();
// Code to be timed
qMyTimer.End();

// This holds the time
double dElapsedTime = qMyTimer.GetTimeInSeconds();