我知道POSIX休眠(x)函数使程序休眠x秒。C++中是否有一个函数可以让程序休眠x毫秒?
当前回答
为什么不使用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;
}
其他回答
纳米睡眠是比usleep更好的选择,它对中断更有弹性。
使用Boost异步输入/输出线程,休眠x毫秒;
#include <boost/thread.hpp>
#include <boost/asio.hpp>
boost::thread::sleep(boost::get_system_time() + boost::posix_time::millisec(1000));
#include <windows.h>
语法:
Sleep ( __in DWORD dwMilliseconds );
用法:
Sleep (1000); //Sleeps for 1000 ms or 1 sec
在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
在Unix中,您可以使用usleep。
在Windows中有“睡眠”。
推荐文章
- 如何强制从另一个SSH会话分离屏幕?
- 什么是“参数依赖查找”(又名ADL,或“Koenig查找”)?
- 公共朋友交换成员函数
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- 如何在Go中使用c++
- 自定义c++分配器的引人注目的例子?
- RAII和c++中的智能指针
- 如何构建和使用谷歌TensorFlow c++ api
- Linux Bash中双&和分号有什么区别?
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 在SSH会话中查找客户端的IP地址
- 在STL地图中,使用map::insert比[]更好吗?
- C++ Linux的想法?
- 如何为Fedora安装g++ ?