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 :)

4 comments:

  1. QPC has some wrinkles on some platform/CPU combinations still in use today. If you have boost available, a version that's portable, safe, and with less shady casting:

    #include <boost/date_time/posix_time/posix_time.hpp>
    #include <iostream>

    int main() {
    using namespace std;
    using namespace boost::posix_time;

    ptime start_time = microsec_clock::universal_time();
    do_something();
    ptime end_time = microsec_clock::universal_time();

    time_duration how_long = end_time - start_time;

    cout << how_long.total_nanoseconds() << '\n';

    return 0;
    }

    ReplyDelete
    Replies
    1. Thanks for that information. Didn't know that.

      Delete
  2. but you dont tell us where to put the code, like some could go before the message loop or after, can you do a tutorial with a window etc and the message loop and timer class?

    ReplyDelete
    Replies
    1. I can just show you where exactly I put it at if you like

      Delete