回答您自己的问题可能是不好的做法,但我想在 Nikko 建议的内容中添加更多内容,因为我没有使用两个建议的库实现该功能。有人可能会在某些时候发现这很有用。
void SleepingExampleTest::sleepInterval(int frequency, int cycles, boost::function<void()> method) {
boost::posix_time::time_duration interval(boost::posix_time::microseconds(1000000 / frequency));
boost::posix_time::ptime timer = boost::posix_time::microsec_clock::local_time() + interval;
boost::this_thread::sleep(timer - boost::posix_time::microsec_clock::local_time());
while(cycles--) {
method();
timer = timer + interval;
boost::this_thread::sleep(timer - boost::posix_time::microsec_clock::local_time());
}
}
希望人们能理解我敲出的这个简单的例子。使用绑定函数只是为了提供灵活性。
似乎在我的机器上以大约 50 微秒的精度工作。在考虑到执行称为精度的方法所需的时间偏差之前,它是几百微秒,所以绝对值得。