I will be doing tutorials on things that may be lacking on the internet. If any of you want to learn something new and dont know how to go about it let me know and I will create a video tutorial on it. Otherwise check my tutorials out in here or in my youtube channel.
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 :)
Subscribe to:
Post Comments (Atom)
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:
ReplyDelete#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;
}
Thanks for that information. Didn't know that.
Deletebut 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?
ReplyDeleteI can just show you where exactly I put it at if you like
Delete