“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..
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…
- 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!