Skip to content

Instantly share code, notes, and snippets.

@m-schwenk
Last active March 17, 2016 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-schwenk/d312c02ec6b230c19dc2 to your computer and use it in GitHub Desktop.
Save m-schwenk/d312c02ec6b230c19dc2 to your computer and use it in GitHub Desktop.
Shows how to use Windows QPC functions (in C99) to obtain the elapsed time in milliseconds.
/*
adapted from:
https://msdn.microsoft.com/en-us/library/dn553408(v=vs.85).aspx#examples_for_acquiring_time_stamps
*/
#include <windows.h>
/*
returns the time in millisecs expired since the last call to this function
because this function needs to initialize it will return 0 on first call.
if in doubt call twice, once before and once after the activity to be timed
if multiple activities are to be timed consecutively one after the other however
one call directly after will suffice
*/
long getElapsedTimeMilSec()
{
LARGE_INTEGER currentTime, ElapsedMicroseconds;
static LARGE_INTEGER formerTime, Frequency;
static BOOL initialized = FALSE;
if (initialized == FALSE)
{
QueryPerformanceFrequency(&Frequency);
QueryPerformanceCounter(&formerTime);
initialized = TRUE;
return 0;
}
QueryPerformanceCounter(&currentTime);
ElapsedMicroseconds.QuadPart = currentTime.QuadPart - formerTime.QuadPart;
// We now have the elapsed number of ticks, along with the
// number of ticks-per-second. We use these values
// to convert to the number of elapsed microseconds.
// To guard against loss-of-precision, we convert
// to microseconds *before* dividing by ticks-per-second.
ElapsedMicroseconds.QuadPart *= 1000000;
ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;
QueryPerformanceCounter(&formerTime);
return (long)ElapsedMicroseconds.QuadPart / 1000;
}
// example below, exclude this from your own code
#include <stdio.h>
int main(void)
{
getElapsedTimeMilSec();
Sleep(1000); // sleeps for approx. 1 second
printf("\"Sleep(1000)\" yielded: %i\n", getElapsedTimeMilSec());
Sleep(2000); // sleeps for approx. 1 second
printf("\"Sleep(2000)\" yielded: %i\n", getElapsedTimeMilSec());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment