在C++中,可以使用以下几种方法让程序休眠指定的时间:
1 使用操作系统相关的方法,如 Windows 中的 Sleep 函数,需要包含 <windows.h> 头文件
#include <windows.h>
// 休眠1000毫秒(1秒)
Sleep(1000);

2 使用头文件 和 中的 sleep_for 函数
#include<chrono>
#include<thread>
// 休眠1秒
std::this_thread::sleep_for(std::chrono::seconds(1));
// 休眠500毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(500));

总结:请注意,以上方法都是阻塞式的,即程序在休眠期间无法进行其他操作。另外,使用 <chrono> 和 <thread> 的方法是较为推荐的,因为它是跨平台的。例如在Cyclonedds这样的开源跨平台的源码中想要加入让程序休眠一段时间的代码的话只能使用第二种,因为第二种方法是跨平台的,而第一种只能限制在了Windows平台

















![[HDLBits] Exams/m2014 q4g](https://img-blog.csdnimg.cn/img_convert/f63e666da5a7a7ce032c242a744414ea.png)