Thomas Sampson

Using a QueryPerformanceTimer in C++

“Query Performance Counters” can be used to create timers within your code, usually used to capture the time it takes to carry out a given function or set of instructions. Query Performance Counters can be particularly useful when you are looking to optimise a piece of code and need to run comparisons on your optimisations.

To start using performance timers first make sure to include the following..

#include <windows.h>
#include “stdio.h”

using namespace std;

Next you need to create some variables to hold the timing data, these are of the type LARGE_INTEGER.

LARGE_INTEGER start, end, freq;

Now we are ready to set up the timer. First pick a place where you are wanting to start and stop your timer. Once you are sure insert the following pieces of code in the appropriate positions

QueryPerformanceCounter(&start); //To start the times

// Code here

QueryPerformanceCounter(&end);  //Same function stops the timer (notice different return variable)

LARGE_INTEGER numTicks=(end.LowPart – start.LowPart); // Save the number of ticks

The amount of time passed by is recorded in “ticks” rather than seconds or milliseconds, we can deal with this later. Ticks are units that relate to the processing speed of your CPU, therefore every machine will have different tick durations and tick speeds. Therefore we need a way to convert ticks into something useful. This is quite a simple calculation as we can query the processor to tell us how many ticks occur per second. This is achieved with the following code and should be placed right after the timer has finished…

QueryPerformanceFrequency(&freq);

So now we have two important numbers…

  1. numTicks
  2. freq (number of ticks per second)

A simple calculation brings us to the following result…

float elapsedTime = (float)ticks/frequency;

Where elapsedTime represents the number of Seconds the timer took!

About these ads

Author: tomtech999

I have recently graduated with a 1st class degree in MComp Games Software Development at Sheffield Hallam University, focusing primarily on application development in C++, with experience in graphics programming, scripting languages, DVCS/VCS and web technology. In my spare time I enjoy Drumming, Reading and Snowboarding!

Comments are closed.

Follow

Get every new post delivered to your Inbox.

Join 91 other followers