2023-05-14 07:00:05

休眠毫秒

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


当前回答

#include <chrono>
#include <thread>

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

记住导入两个标头。

其他回答

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

对于C,在gcc中使用///。

#包括<windows.h>

然后使用Sleep();///Sleep()带有大写S,而不是Sleep()带有S。

//睡眠(1000)可能是1秒///。

clang支持sleep(),sleep(1)表示1秒延时/等待。

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

为什么不使用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;
}

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