c++ - C++ 的跨平台 sleep 功能

标签 c++ cross-platform sleep

是否可以使用宏制作跨平台的 sleep 代码? 例如

#ifdef LINUX
#include <header_for_linux_sleep_function.h>
#endif
#ifdef WINDOWS
#include <header_for_windows_sleep_function.h>
#endif
...
Sleep(miliseconds);
...

最佳答案

是的。但这仅适用于 C++11later .

#include <chrono>
#include <thread>
...
std::this_thread::sleep_for(std::chrono::milliseconds(ms));

其中 ms 是您想要休眠的时间,以毫秒为单位。

您也可以将 milliseconds 替换为 nanosecondsmicrosecondssecondsminutes小时。 (这些是 std::chrono::duration 类型的特化。)

更新:C++14 ,如果你睡了一段时间,例如 100 毫秒,std::chrono::milliseconds(100) 可以写成 100ms。这是由于 user defined literals ,在 C++11 中引入.在 C++14 chrono 库已扩展为包含以下用户定义的文字:

实际上这意味着你可以写出这样的东西。

#include <chrono>
#include <thread>
using namespace std::literals::chrono_literals;

std::this_thread::sleep_for(100ms);

请注意,虽然 using namespace std::literals::chrono_literals 提供了最少的 namespace pollution , 这些运算符在 using namespace std::literalsusing namespace std::chrono 时也可用。

关于c++ - C++ 的跨平台 sleep 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10918206/

相关文章:

ruby-on-rails - Rspec 测试需要 sleep 才能工作

c++ - C++ 容器的一般用例

c++ - 整数到字符串优化函数?

c++ - stringstream >> 十六进制的 uint8_t? C++

xml - 如何从 shell 执行 XPath 单行代码?

java - Java中延迟函数调用而不暂停应用程序

c++ - 与静态方法中的 decltype(*this) 等价?

windows - Linux 和 Windows 下 emacs 中 webdev 的可靠配置?

ios - iOS 的 FIONBIO 值是多少,以阻止/取消阻止套接字?

Python time.sleep - 永不醒来