C++中的睡眠操作,平台:windows
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7946092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sleep operation in C++, platform : windows
提问by Pumpkin
I want to perform the above mentioned operation in Milliseconds as the unit. Which library and function call should I prefer ?
我想以毫秒为单位执行上述操作。我应该更喜欢哪个库和函数调用?
Ty.
泰。
回答by sehe
Or if you are using Visual Studio 2010 (or another c++0x aware compiler) use
或者,如果您使用的是 Visual Studio 2010(或其他 C++0x 感知编译器),请使用
#include <thread>
#include <chrono>
std::this_thread::sleep();
// or
std::this_thread::sleep_for(std::chrono::milliseconds(10));
With older compilers you can have the same convenience using the relevant Boost Libraries
对于较旧的编译器,您可以使用相关的Boost 库获得同样的便利
Needless to saythe major benefit here is portabilityand the ease of converting the delay parameter to 'human' units.
不用说,这里的主要好处是便携性和将延迟参数转换为“人类”单位的简便性。
回答by Adrien Plisson
the windows task scheduler has a granularity far above 1ms (generally, 20ms). you can test this by using the performance counter to measure the time really spent in the Sleep()
function. (using QueryPerformanceFrequency()
and QueryPerformanceCounter()
allows you to measure time down to the nanosecond). note that Sleep(0)
makes the thread sleep for the shortest period of time possible.
windows任务调度器的粒度远高于1ms(一般为20ms)。您可以通过使用性能计数器来测量实际花费在Sleep()
函数中的时间来测试这一点。(使用QueryPerformanceFrequency()
并QueryPerformanceCounter()
允许您将时间测量到纳秒)。请注意,这Sleep(0)
会使线程在尽可能短的时间内休眠。
however, you can change this behavior by using timeBeginPeriod()
, and passing a 1ms period. now Sleep(0)
should return much faster.
但是,您可以通过使用timeBeginPeriod()
, 并传递 1ms 周期来更改此行为。现在Sleep(0)
应该返回得更快。
note that this function call was made for playing multimedia streams with a better accuracy. i have never had any problem using this, but the need for such a fast period is quite rare. depending on what you are trying to achieve, there may be better ways to get the accuracy you want, without resorting to this "hack".
请注意,此函数调用是为了更准确地播放多媒体流。我使用这个从来没有遇到过任何问题,但是需要这么快的时间是非常罕见的。根据您要实现的目标,可能有更好的方法来获得您想要的准确性,而无需求助于这种“黑客”。
回答by ksming
Er, the sleep() function from win32 api?
呃,win32 api 的 sleep() 函数?
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298%28v=vs.85%29.aspx