我知道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;
}
其他回答
使用Boost异步输入/输出线程,休眠x毫秒;
#include <boost/thread.hpp>
#include <boost/asio.hpp>
boost::thread::sleep(boost::get_system_time() + boost::posix_time::millisec(1000));
选择调用是一种提高精度的方法(睡眠时间可以以纳秒为单位)。
注意,没有毫秒的标准C API,因此(在Unix上)您必须接受usleep,它接受微秒:
#include <unistd.h>
unsigned int microseconds;
...
usleep(microseconds);
作为POSIX系统的Win32替代品:
void Sleep(unsigned int milliseconds) {
usleep(milliseconds * 1000);
}
while (1) {
printf(".");
Sleep((unsigned int)(1000.0f/20.0f)); // 20 fps
}
在具有选择功能的平台(POSIX、Linux和Windows)上,您可以执行以下操作:
void sleep(unsigned long msec) {
timeval delay = {msec / 1000, msec % 1000 * 1000};
int rc = ::select(0, NULL, NULL, NULL, &delay);
if(-1 == rc) {
// Handle signals by continuing to sleep or return immediately.
}
}
然而,现在有更好的选择。
推荐文章
- 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()更好?