2014-09-22 74 views
3

我使用非常簡單的代碼中的iOS升壓期限計時器到期不準確的iOS

結果測試截止時間定時器是不準確的: 在桌面或模擬器,其結果將是20或21,在移動,結果 會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

在桌面或模擬器,其結果將是移動20或21, ,其結果將是24,25, 我想實現播放器的庫,5ms的錯誤是不允許的。 – PatrickSCLin 2014-09-22 06:24:10

+0

什麼是默認** ['tolerance'](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/index.html#//apple_ref/occ/instp/NSTimer/tolerance)**值? – sehe 2014-09-22 06:35:35

+0

它應該每20毫秒觸發一次 – PatrickSCLin 2014-09-22 06:38:53

回答

3

您可能需要使用http://www.boost.org/doc/libs/1_56_0/doc/html/boost_asio/reference/high_resolution_timer.htmlchrono::high_resolution_clock代替:

看到它Live On Coliru

輸出爲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(); 
} 
+0

修正了現場演示:http://coliru.stacked-crooked.com/a/d58a43078383d31b – sehe 2014-09-22 09:52:46

+1

真棒!它適用於iOS! – PatrickSCLin 2014-09-22 14:12:02

+0

你有沒有在Mac上試過這段代碼? 當我在真實設備上運行此代碼時,它總是返回「20」或「21」 ,但它在您的演示中返回完美,總是返回「20」 – PatrickSCLin 2014-09-22 16:12:21