0

I need to do something in my program every 10 seconds and I don't know how to do it in C++ Console Application. In C# I could just create a timer but I'm struggling here now...

sleep(); is not an option because as far as I know it makes your program inactive for X seconds, I need my app to be active and working, calculating all the time.

Please help me with this little (or big?) problem, I'm very new to C++ and learning ATM :)

So I've set up BOOST libraries and now I'm doing something like this.

boost::timer t;

while (true)
{
    if (t.elapsed() > 1)
    {
        cout << t.elapsed() << endl;
        t.restart();
    }
}

Is it good enough or there should be much better way? Oh no, it's very bad, eating 25% of my CPU non-stop. :(

Stan
  • 25,744
  • 53
  • 164
  • 242
  • 4
    sleep() is an option if you put it in a separate thread. – Benjamin Lindley Jan 31 '11 at 20:20
  • How exact does that 10 seconds have to be? Since your app is "calculating all the time", you can probably just throw an if statement in one of your outer loops, check the current time, if it's after the scheduled time then call the periodic work function and adjust the scheduled time for the next time it should run. – Ben Voigt Jan 31 '11 at 21:36
  • Off of what both PigBen and Ben have said, how exact is necessary? If you're in just one thread, you can probably put some sort of sleep in there (10ms will probably do). In windows it would look like `Sleep(10);` or in *nix it would look like `usleep(10*1000); // 10microseconds * 1000 = 10 milliseconds` – RageD Feb 01 '11 at 00:04

2 Answers2

6

Boost has a timer library.

In fact, if you haven't come across Boost already, I'm sure you'll find it very useful.


To do an event based timer, you should look at this answer.

Community
  • 1
  • 1
ocodo
  • 29,401
  • 18
  • 105
  • 117
  • Thanks, I think I'll stick with Boost. Seems very rich in functions and not so hard to use. – Stan Jan 31 '11 at 20:36
  • Hey, so I got it up and running and now I see the timer. Please see if my timer method is good enough :) – Stan Jan 31 '11 at 21:20
1

The easy way is to create a new thread (man pthreads if you are using Linux) and do this stuff in it.

Here is some information and examples how to use POSIX threads - http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_create.3.html

Elalfer
  • 5,312
  • 20
  • 25