2023-05-14 07:00:05

休眠毫秒

我知道POSIX休眠(x)函数使程序休眠x秒。C++中是否有一个函数可以让程序休眠x毫秒?


当前回答

在具有选择功能的平台(POSIX、Linux和Windows)上,您可以执行以下操作:

void sleep(unsigned long msec) {
    timeval delay = {msec / 1000, msec % 1000 * 1000};
    int rc = ::select(0, NULL, NULL, NULL, &delay);
    if(-1 == rc) {
        // Handle signals by continuing to sleep or return immediately.
    }
}

然而,现在有更好的选择。

其他回答

在C++11中,您可以使用标准库设施来实现这一点:

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

清晰易读,无需猜测sleep()函数使用的单位。

使用Boost异步输入/输出线程,休眠x毫秒;

#include <boost/thread.hpp>
#include <boost/asio.hpp>

boost::thread::sleep(boost::get_system_time() + boost::posix_time::millisec(1000));

在具有选择功能的平台(POSIX、Linux和Windows)上,您可以执行以下操作:

void sleep(unsigned long msec) {
    timeval delay = {msec / 1000, msec % 1000 * 1000};
    int rc = ::select(0, NULL, NULL, NULL, &delay);
    if(-1 == rc) {
        // Handle signals by continuing to sleep or return immediately.
    }
}

然而,现在有更好的选择。

#include <windows.h>

语法:

Sleep (  __in DWORD dwMilliseconds   );

用法:

Sleep (1000); //Sleeps for 1000 ms or 1 sec

选择调用是一种提高精度的方法(睡眠时间可以以纳秒为单位)。