我知道POSIX休眠(x)函数使程序休眠x秒。C++中是否有一个函数可以让程序休眠x毫秒?
当前回答
这个问题由来已久,但我设法找到了一个在我的应用程序中实现这一点的简单方法。您可以创建如下所示的C/C++宏:
#ifndef MACROS_H
#define MACROS_H
#include <unistd.h>
#define msleep(X) usleep(X * 1000)
#endif // MACROS_H
其他回答
作为POSIX系统的Win32替代品:
void Sleep(unsigned int milliseconds) {
usleep(milliseconds * 1000);
}
while (1) {
printf(".");
Sleep((unsigned int)(1000.0f/20.0f)); // 20 fps
}
在C++11中,您可以使用标准库设施来实现这一点:
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));
清晰易读,无需猜测sleep()函数使用的单位。
根据您的平台,您可以使用usleep或nanosleep。usleep已被弃用,并已从最新的POSIX标准中删除;纳米睡眠是优选的。
使用Boost异步输入/输出线程,休眠x毫秒;
#include <boost/thread.hpp>
#include <boost/asio.hpp>
boost::thread::sleep(boost::get_system_time() + boost::posix_time::millisec(1000));
为什么不使用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;
}
推荐文章
- 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()更好?