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 API,因此(在Unix上)您必须接受usleep,它接受微秒:

#include <unistd.h>

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

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

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

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

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

在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

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