怎么實現一個精準的Timer?我寫了如下的代碼進行測試。1. 在主線程中。NSTimer *tiemer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(output) userInfo:nil repeats:YES];
- (void) output{ NSLog(@"-------------");
}發現間隔時間大概在正負5毫秒之間徘徊。就像這樣:2013-05-02 16:25:32.550 TestDemoArc[21139:907] -------------2013-05-02 16:25:33.549 TestDemoArc[21139:907] -------------2013-05-02 16:25:34.554 TestDemoArc[21139:907] -------------2013-05-02 16:25:35.555 TestDemoArc[21139:907] -------------如果在主線程中做一些操作,比如: int j = 0;
for (int i = 0; i<100000000; i++) {
j = j+i; }時間間隔會變為兩秒。就像這樣:2013-05-02 16:38:32.437 TestDemoArc[21207:907] -------------2013-05-02 16:38:34.437 TestDemoArc[21207:907] -------------2013-05-02 16:38:36.437 TestDemoArc[21207:907] -------------2013-05-02 16:38:38.439 TestDemoArc[21207:907] -------------2013-05-02 16:38:40.437 TestDemoArc[21207:907] -------------當然,用block放到子線程里就只有1毫秒左右的偏差了?,F在想問怎么做一個Timer,保證有在1毫秒以下的偏差。
2 回答

絕地無雙
TA貢獻1946條經驗 獲得超4個贊
IOS中可以使用"mach_absolute_time"獲取到CPU的tickcount的計數值,可以通過"mach_timebase_info"函數獲取到納秒級的精確度 代碼如下: uint64t start = 0; uint64t end = 0; uint64_t elapsed = 0;
mach_timebase_info_t timeBaseInfo = mach_timebase_info(info);start = mach_absolute_time();// dosomething // .....end = mach_absolute_time();elapsed = end - start;// convert to nanoseconds uint64_t elapsedNanoSeconds = elapsed * sTimebaseInfo.numer / sTimebaseInfo.denom;
但是CPU線程之間的調度肯定要花費時間,所以只能盡可能的精確。

郎朗坤
TA貢獻1921條經驗 獲得超9個贊
計時器不準確的原因是,計時器只有在 runLoop 的一次循環中被檢查,所以如果在上次循環中做了什么耗時的操作,那么計時器就被延后執行了。
正確的方法應該是新開一個線程,然后在新開的線程里設定一個 timer,并執行。
__block TestViewController *blockSelf = self;dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ blockSelf->_timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:blockSelf selector:@selector(caculateLeftTimeForTomorrow) userInfo:nil repeats:YES] ; [[NSRunLoop currentRunLoop] addTimer:blockSelf->_timer forMode:NSDefaultRunLoopMode]; [[NSRunLoop currentRunLoop] run]; });
- 2 回答
- 0 關注
- 331 瀏覽
添加回答
舉報
0/150
提交
取消