需要更好的等待解决方案 [英] Need a better wait solution
问题描述
最近我一直在用C ++写一个程序,ping三个不同的网站,然后根据通过或失败,它将等待5分钟或30秒,然后再次尝试。
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.
目前我一直在使用ctime库和以下函数来处理我的等待,然而根据我的CPU表这是一个不能接受的解决方案。
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) {}
}
为什么这个解决方案是不可接受的是因为根据我的CPU计算机程序运行在我的CPU的48%到50%的等待。我有一个Athlon 64 x2 1.2ghz处理器。有没有办法我的谦虚130线程序甚至应该接近50%。
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.2ghz processor. There is no way my modest 130 line program should even get near 50%.
我想知道的是如何更好地写我的等待函数,以便它只使用最少的资源?谢谢。
What I am asking to know is how can I write my wait function better so that it is only using minimal resources? Thank you.
推荐答案
为了保持便携性,您可以使用 Boost :: Thread 用于睡觉:
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;
}
这篇关于需要更好的等待解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!