3
votes

Recently I have been writing a program in C++ that pings three different websites and then depending on pass or fail it will wait 5 minutes or 30 seconds before it tries again.

Currently I have been using the ctime library and the following function to process my waiting. However, according to my CPU meter this is an unacceptable solution.

void wait (int seconds)
{
   clock_t endwait;
   endwait = clock () + seconds * CLOCKS_PER_SEC;
   while (clock () < endwait) {}
}

The reason why this solution is unacceptable is because according to my CPU meter the program runs at 48% to 50% of my CPU when waiting. I have a Athlon 64 x2 1.2 GHz processor. There is no way my modest 130 line program should even get near 50%.

How can I write my wait function better so that it is only using minimal resources?

5
Does this answer your question? Sleep for millisecondsCris Luengo

5 Answers

13
votes

To stay portable you could use Boost::Thread for sleeping:

#include <boost/thread/thread.hpp>

int main()
{
    //waits 2 seconds
    boost::this_thread::sleep( boost::posix_time::seconds(1) );
    boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );

    return 0;
}
6
votes

With the C++11 standard the following approach can be used:

std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::this_thread::sleep_for(std::chrono::seconds(100));

Alternatively sleep_until could be used.

3
votes

Use sleep rather than an empty while loop.

3
votes

Just to explain what's happening: when you call clock() your program retrieves the time again: you're asking it to do that as fast as it can until it reaches the endtime... that leaves the CPU core running the program "spinning" as fast as it can through your loop, reading the time millions of times a second in the hope it'll have rolled over to the endtime. You need to instead tell the operating system that you want to be woken up after an interval... then they can suspend your program and let other programs run (or the system idle)... that's what the various sleep functions mentioned in other answers are for.

0
votes

There's Sleep in windows.h, on *nix there's sleep in unistd.h.

There's a more elegant solution @ http://www.faqs.org/faqs/unix-faq/faq/part4/section-6.html