Thomas Sampson

Leave a comment

C++ Code Timing Snippet

#include <windows.h>

int main(int argc, char* argv[])
    __int64 start, end, frequency;




    float time_in_seconds=(end-start) / (float)frequency;

    return 0;

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…


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!