2023-05-14 07:00:05

休眠毫秒

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


当前回答

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

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

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

其他回答

我使用这个:

#include <thread>
#define sleepms(val) std::this_thread::sleep_for(val##ms)

例子:

sleepms(200);

根据您的平台,您可以使用usleep或nanosleep。usleep已被弃用,并已从最新的POSIX标准中删除;纳米睡眠是优选的。

为什么不使用time.h库?在Windows和POSIX系统上运行(不要在生产中使用此代码!):

CPU保持空闲状态:

#include <iostream>
#ifdef _WIN32
    #include <windows.h>
#else
    #include <unistd.h>
#endif // _WIN32

using namespace std;

void sleepcp(int milliseconds);

void sleepcp(int milliseconds) // Cross-platform sleep function
{
    #ifdef _WIN32
        Sleep(milliseconds);
    #else
        usleep(milliseconds * 1000);
    #endif // _WIN32
}
int main()
{
    cout << "Hi! At the count to 3, I'll die! :)" << endl;
    sleepcp(3000);
    cout << "urrrrggghhhh!" << endl;
}
#include <chrono>
#include <thread>

std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // sleep for 1 second

记住导入两个标头。

纳米睡眠是比usleep更好的选择,它对中断更有弹性。