C++中如何让程序休眠自定义的时长

在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平台

猜你喜欢

转载自blog.csdn.net/qq_42595610/article/details/132180112
今日推荐