我知道POSIX休眠(x)函数使程序休眠x秒。C++中是否有一个函数可以让程序休眠x毫秒?
当前回答
在C++11中,您可以使用标准库设施来实现这一点:
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));
清晰易读,无需猜测sleep()函数使用的单位。
其他回答
根据您的平台,您可以使用usleep或nanosleep。usleep已被弃用,并已从最新的POSIX标准中删除;纳米睡眠是优选的。
在Unix中,您可以使用usleep。
在Windows中有“睡眠”。
纳米睡眠是比usleep更好的选择,它对中断更有弹性。
为什么不使用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;
}
在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
推荐文章
- decltype(auto)的一些用途是什么?
- Shared_ptr转换为数组:应该使用它吗?
- Printf与std::字符串?
- 在Bash中检查变量是否存在于列表中
- JavaScript中有睡眠/暂停/等待功能吗?
- 禁用复制构造函数
- 查看PS命令的全部输出
- 只接受特定类型的c++模板
- c#和Java中的泛型有什么不同?和模板在c++ ?
- Linux命令将域名转换为IP
- c++ 11中的递归lambda函数
- 在c++中指针使用NULL或0(零)吗?
- 在c++中,如何将int值附加到字符串中?
- 如何从命令行在windows中找到mysql数据目录
- 就性能而言,使用std::memcpy()还是std::copy()更好?