【发布时间】:2015-04-19 05:23:20
【问题描述】:
近一个星期以来,我一直在自学 C++,以提前学习我即将在大学开设的 C++ 课程。现在我在我的这个项目中,我想看看我是否可以实现准确的延迟或睡眠时间少于 1 毫秒。
我对如何在 Windows 中实现这一点进行了一些研究,并看到了类似的答案:
- 睡眠不准确
- 在 Windows 中睡眠时间不能少于 1 毫秒,但在 *UX 平台中可能
- 在 C++ 中使用 boost 库
所以我尝试在 Visual Studio 2013 中获取 boost 库,并通过 gob00st 找到了这个 sn-p c++ Implementing Timed Callback function
我稍微修改了deadline类:
class Deadline
{
int i = 0;
public:
Deadline(deadline_timer &timer) : t(timer) {
wait();
}
void timeout(const boost::system::error_code &e) {
if (e)
return;
cout << i++ << endl;
wait();
}
然后改了这一行
void wait() {
t.expires_from_now(boost::posix_time::seconds(1)); //repeat rate here
t.async_wait(boost::bind(&Deadline::timeout, this, boost::asio::placeholders::error));
}
对这些
void wait() {
t.expires_from_now(boost::posix_time::microseconds(100)); //repeat rate here
t.async_wait(boost::bind(&Deadline::timeout, this, boost::asio::placeholders::error));
}
运行它,它会在 10 秒后准确地输出数字 10000,所以看起来我仍然被困在 Windows 中的这个限制,你不能睡眠或延迟少于 1 毫秒。
然后我发现这个答案说我可以使用 Boost 的 CPU 精度计时器来实现这一点。 Accurate delays between notes when synthesising a song
如何编辑代码 sn-p 以使用 Cpu 精度计时器而不是使用 boost 的 asio 计时器?
【问题讨论】:
-
寻找 std::chrono 设施
-
抢占式操作系统中的正常进程无法休眠准确的时间。您要实现的目标需要实时功能。你需要那个干什么?
-
现在没有什么特别的,我只是想看看我能做什么的限制。如果我需要在 windows 中使用小于 1 毫秒的时间延迟,还有一个我可以在未来使用的模板会很好