Expiration Timer Expires Inaccurately in iOS

I am using very simple code to check due date timer in iOS

The result is not accurate: In Desktop or Simulator, the result will be 20 or 21, in Mobile, the result will be 24, 25, I would like to implement the player's library, so a 5ms error is unacceptable.

How to make the timer more accurate in iOS?

Here is the code:

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));
}

      

+3


source to share


1 answer


You can use http://www.boost.org/doc/libs/1_56_0/doc/html/boost_asio/reference/high_resolution_timer.html instead and chrono::high_resolution_clock

:

Watch Live On Coliru



Conclusion run time: 20

without exceptions.

#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();
}

      

+3


source







All Articles