简体   繁体   English

在C ++,platform:windows中进行睡眠操作

[英]Sleep operation in C++, platform : windows

I want to perform the above mentioned operation in Milliseconds as the unit. 我想以毫秒为单位执行上述操作。 Which library and function call should I prefer ? 我更喜欢哪个库和函数调用?

Ty. TY。

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 say the major benefit here is portability and the ease of converting the delay parameter to 'human' units. 毋庸置疑,这里的主要好处是可移植性以及将延迟参数转换为“人”单元的便利性。

您可以使用Win32 API中的Sleep功能。

the windows task scheduler has a granularity far above 1ms (generally, 20ms). Windows任务调度程序的粒度远远超过1毫秒(通常为20毫秒)。 you can test this by using the performance counter to measure the time really spent in the Sleep() function. 您可以使用性能计数器来测量这个,以测量Sleep()函数中真正花费的时间。 (using QueryPerformanceFrequency() and QueryPerformanceCounter() allows you to measure time down to the nanosecond). (使用QueryPerformanceFrequency()QueryPerformanceCounter()可以测量低至纳秒的时间)。 note that Sleep(0) makes the thread sleep for the shortest period of time possible. 请注意, Sleep(0)使线程在尽可能短的时间内休眠。

however, you can change this behavior by using timeBeginPeriod() , and passing a 1ms period. 但是,您可以通过使用timeBeginPeriod()并传递1ms周期来更改此行为。 now Sleep(0) should return much faster. 现在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". 根据你想要达到的目标,可能有更好的方法来获得你想要的准确性,而不是诉诸于这种“黑客”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM