OS X 上 C++ 的睡眠操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19439672/
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++ on OS X
提问by m_j
I want to perform the above mentioned operation in milliseconds as the unit. Which library and function call should I prefer?
我想以毫秒为单位执行上述操作。我应该更喜欢哪个库和函数调用?
回答by NHDaly
EDIT 2017: C++11 sleep_for
is the right way to do this. Please see Xornad's answer, below.
编辑 2017:C++11sleep_for
是正确的方法。请参阅下面的 Xornad 的回答。
C++03:
C++03:
Since Mac OS X is Unix-based, you can almost always just use the standard linux functions!
由于 Mac OS X 是基于 Unix 的,您几乎总是可以使用标准的 linux 功能!
In this case you can use usleep
(which takes a time in microseconds) and just multiply your milliseconds by 1000 to get microseconds.
在这种情况下,您可以使用usleep
(以微秒为单位的时间)并将毫秒乘以 1000 以获得微秒。
#include <unistd.h>
int main () {
usleep(1000); // will sleep for 1 ms
usleep(1); // will sleep for 0.001 ms
usleep(1000000); // will sleep for 1 s
}
For more info on this function, check out the Linux man page:
有关此功能的更多信息,请查看 Linux 手册页:
回答by Xornand
If you have C++11 support in your compiler, you can use the sleep_for
and avoid having to use an OS specific API. (http://en.cppreference.com/w/cpp/thread/sleep_for)
如果您的编译器支持 C++11,您可以使用sleep_for
并且避免使用特定于操作系统的 API。(http://en.cppreference.com/w/cpp/thread/sleep_for)
#include <thread>
#include <chrono>
int main()
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
return 0;
}