我知道POSIX休眠(x)函数使程序休眠x秒。C++中是否有一个函数可以让程序休眠x毫秒?
当前回答
#include <windows.h>
语法:
Sleep ( __in DWORD dwMilliseconds );
用法:
Sleep (1000); //Sleeps for 1000 ms or 1 sec
其他回答
我使用这个:
#include <thread>
#define sleepms(val) std::this_thread::sleep_for(val##ms)
例子:
sleepms(200);
选择调用是一种提高精度的方法(睡眠时间可以以纳秒为单位)。
从C++14开始,使用std及其数字文本:
#include <chrono>
#include <thread>
using namespace std::chrono_literals;
std::this_thread::sleep_for(123ms);
对于C,在gcc中使用///。
#包括<windows.h>
然后使用Sleep();///Sleep()带有大写S,而不是Sleep()带有S。
//睡眠(1000)可能是1秒///。
clang支持sleep(),sleep(1)表示1秒延时/等待。
在C++11中,您可以使用标准库设施来实现这一点:
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));
清晰易读,无需猜测sleep()函数使用的单位。
推荐文章
- 为什么这个结合赋值和相等检查的if语句返回true?
- 如何找到Java堆大小和内存使用(Linux)?
- 遍历带空格的文件列表
- cplusplus.com给出的错误、误解或坏建议是什么?
- Bash:无限睡眠(无限阻塞)
- 如何使Python脚本在Linux中像服务或守护进程一样运行
- 找出质数最快的算法是什么?
- 如何使用文件的行作为命令的参数?
- time_t最终的类型定义是什么?
- c++枚举类可以有方法吗?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 如何使用cut为分隔符指定更多的空格?