2023-05-14 07:00:05

休眠毫秒

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


当前回答

从C++14开始,使用std及其数字文本:

#include <chrono>
#include <thread>

using namespace std::chrono_literals;

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

其他回答

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

在Unix中,您可以使用usleep。

在Windows中有“睡眠”。

注意,没有毫秒的标准C API,因此(在Unix上)您必须接受usleep,它接受微秒:

#include <unistd.h>

unsigned int microseconds;
...
usleep(microseconds);

在C++中休眠程序的方法是sleep(int)方法。它的头文件是#include“windows.h”

例如:

#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;

int main()
{
    int x = 6000;
    Sleep(x);
    cout << "6 seconds have passed" << endl;
    return 0;
}

它的睡眠时间以毫秒为单位,没有限制。

Second = 1000 milliseconds
Minute = 60000 milliseconds
Hour = 3600000 milliseconds

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