Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » Timer

This thread is locked; no one can reply to it. rss feed Print
Timer
xinco1
Member #8,061
December 2006

Whats the best way of telling when 10 seconds has gone by,for example?

kazzmir
Member #1,786
December 2001
avatar

rest( 10 * 1000 );

Do you want to do something while 10 seconds is going by or just wait for 10 seconds? If the former you can set up a timer with

increment a variable every tick and then when the variable * ticks reaches 10 seconds you know 10 seconds will have past.

Billybob
Member #3,136
January 2003

Or ...

int begin_time = time(NULL);
while(time(NULL) - begin_time < 10)
{
     // do stuff
}

If you plan to do very little in the loop, and don't want to eat up all the CPU, use a rest statement in the loop:

int begin_time = time(NULL);
while(time(NULL) - begin_time < 10)
{
     // do stuff
     rest(1);
}

ImLeftFooted
Member #3,935
October 2003
avatar

Timer::time_t t = timer.secs();

...

if(timer.secs() - t > 9)
  .. 10 seconds have elapsed ..

Even easier:

stopwatch sw;
sw.start(10000);

..

if(sw.check())
  .. 10 seconds have elapsed ..

If you want either of these classes I can give them to you.

Goalie Ca
Member #2,579
July 2002
avatar

http://www.boost.org/libs/timer/timer.htm

It's cross platform. I can't recall if this particular boost lib will be in the next C++ standard but its probably a good shot. It's resolution depends on OS's but windows and *nix are both millisecond tickers IIRC.

from the site:

1Synopsis
2 
3#include <boost/timer.hpp>
4namespace boost {
5class timer {
6 public:
7 timer(); // postcondition: elapsed()==0
8 // compiler generated copy constructor, copy assignment, and dtor apply
9 void restart(); // post: elapsed()==0
10 double elapsed() const; // return elapsed time in seconds
11 
12 double elapsed_max() const; // return estimated maximum value for elapsed()
13 // Portability warning: elapsed_max() may return too high a value on systems
14 // where std::clock_t overflows or resets at surprising values.
15 
16 double elapsed_min() const; // return minimum value for elapsed()
17 }; // timer
18} // namespace boost

-------------
Bah weep granah weep nini bong!

Go to: