我使用非常简单的代码来测试iOS中的截止日期计时器
结果不准确: 在桌面或模拟器中,结果将是20或21,在Mobile中 将是24,25,我想实现一个播放器库,所以5ms错误 是不可接受的。
如何在iOS上使计时器更准确?
以下是代码:
boost::thread* _thread;
boost::asio::deadline_timer* _timer;
boost::asio::io_service _io_service;
boost::posix_time::ptime _lastTime;
void test()
{
_timer = new boost::asio::deadline_timer(_io_service);
_timer->expires_from_now(boost::posix_time::milliseconds(0));
_timer->async_wait(boost::bind(case1));
_thread = new boost::thread(boost::bind(&boost::asio::io_service::run, &_io_service));
}
void case1()
{
boost::posix_time::ptime currentTime = boost::posix_time::microsec_clock::local_time();
if (_lastTime.is_not_a_date_time() == false) {
boost::posix_time::time_duration diff = currentTime - _lastTime;
std::cout << "run time: " << diff.total_milliseconds() << std::endl;
}
_lastTime = boost::posix_time::microsec_clock::local_time();
_timer->expires_from_now(boost::posix_time::milliseconds(20));
_timer->async_wait(boost::bind(case1));
}
答案 0 :(得分:4)
您可能希望改为使用http://www.boost.org/doc/libs/1_56_0/doc/html/boost_asio/reference/high_resolution_timer.html和chrono::high_resolution_clock
:
输出为run time: 20
,没有例外。
#include <boost/asio.hpp>
#include <boost/chrono.hpp>
#include <boost/bind.hpp>
#include <boost/asio/high_resolution_timer.hpp>
typedef boost::chrono::high_resolution_clock hrc;
using boost::chrono::duration_cast;
using boost::chrono::milliseconds;
boost::asio::io_service io_service_;
boost::asio::high_resolution_timer timer_(io_service_);
hrc::time_point lastTime_ {};
void case1(boost::system::error_code ec)
{
hrc::time_point currentTime = hrc::now();
if (lastTime_.time_since_epoch().count()) {
hrc::duration diff = currentTime - lastTime_;
std::cout << "run time: " << duration_cast<milliseconds>(diff).count() << std::endl;
}
lastTime_ = hrc::now();
timer_.expires_from_now(milliseconds(20));
timer_.async_wait(boost::bind(case1, boost::asio::placeholders::error));
}
void test()
{
timer_.expires_from_now(milliseconds(0));
timer_.async_wait(boost::bind(case1, boost::asio::placeholders::error));
io_service_.run();
}
int main()
{
test();
}