Saturday, March 31, 2012

C++ Timer Class


Hey guys.  This my blog on how to create a timer in C++.  You can use this in order to get delta time if you like.

include the windows.h file:
#include <windows.h>

you would need to create two variables like so:

float freq_;
unsigned __int64 baseTime_;

You will initialize them in a contructor or initialize function:

unsigned __int64 pf;
QueryPerformanceFrequency( (LARGE_INTEGER *)&pf );
freq_ = 1.0f / (float)pf;
QueryPerformanceCounter( (LARGE_INTEGER *)&baseTime_ );

Basically the QueryPerformanceFrequency will get the high resolution counter's accuracy and
QueryPerformanceCounter is basically the elapsed time since when the program started running

Create a function to get your seconds:

float seconds()
{
unsigned __int64 val;
QueryPerformanceCounter( (LARGE_INTEGER *)&val );
float dt = (float)(val - baseTime_) * freq_ / 60.0f;
baseTime_ = val;

return dt;
}



from this you can also get your milliseconds.

Enjoy :)