c++time-wait

Need a better wait solution


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?


Solution

  • Update in 2023: Nowadays you'd probably not use Boot anymore for this task since the C++ Standard library added native support for sleeping back in C++11. Please check the more appropriate answers below.

    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;
    }