Need a better wait solution

只愿长相守 提交于 2019-12-10 09:39:44

问题


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?


回答1:


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



回答2:


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:


Use sleep rather than an empty while loop.




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/4103707/need-a-better-wait-solution

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!