Skip to main content
GameDev.net gamedev.net
🔒 Locked

C++ Timer

Started by AhmedSaleh Sep 19, 2011 at 6:37 PM 6 replies 2k views
Original Post
AhmedSaleh
AhmedSaleh
Hi All,
I would like to start a timer, and after passing number of seconds, it should call something else. Sure a timer that is can't block the main loop of the game. I would like to know the best method for achieving that
Game Programming is the process of converting dead pictures to live ones .
Antheus
Antheus
time_to_trigger = 0;
while (running) {
if (now() > time_to_trigger) {
do_action();
time_to_trigger = now() + delay;
}
// the rest
}


The only problem is how to implement now(). Since C++ relies on OS to provide timing facilities, clock() is frequently used. It's C, but somewhat portable. OS-specific variations exist.
iMalc
iMalc
Your best option is probably to include it in the main loop of the game.

But otherwise you'd need to go down the route of multi-threading which is not an easy thing to take on if you're unfamiliar with it.
the_edd
the_edd

The only problem is how to implement now(). Since C++ relies on OS to provide timing facilities, clock() is frequently used.

I discovered recently that on Mac OS X clock() returns CPU time which is like not what's wanted, especially in a threaded application on a multicore machine. It seems to be a legitimate interpretation of the standard, too. So tread carefully with that one.
Red Ant
Red Ant

I discovered recently that on Mac OS X clock() returns CPU time which is like not what's wanted, especially in a threaded application on a multicore machine. It seems to be a legitimate interpretation of the standard, too. So tread carefully with that one.


IMO it does that on Windows, too. If you take the time using clock(), then halt your process in a debugger, then resume the process and take the time again, you will see that the difference is not the time that has elapsed in the real world but the amount of time the process has actually used the CPU. So yeah, clock() is not really a suitable tool for that purpose.
ApochPiQ
ApochPiQ
Depending on your chosen language and platform, there may be alternatives, but I second the suggestion that you stick with a simple timestamp check to avoid multithreading.
Blodyavenger
Blodyavenger
If you need that time for a game, then I suggest you implement your own timer.
I calculate ms with delta time.

I create new timer like this

CTimer * tmrTime = new CTimer(2000); // 2000 = every 2000ms even will occur;

In the update I call next functions then

if ( tmrTime->Occurs(dt) )
{
//what happens every 2000ms
}


Behind that function lies the next code
bool CTimer::Occurs(float dt)
{
time += 1000 * dt;
if(time >= maxTime) // maxTime = time that we set in constructor
{
time = 0;
return true;
}

return false;
}


I hope that helps

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.