今天看到一個(gè)有意思的問題:NStimer準(zhǔn)嗎嫁蛇?如果不準(zhǔn)該怎樣實(shí)現(xiàn)一個(gè)精確的NSTimer?
既然這樣問了,那從題目的角度出發(fā)露该,NSTimer肯定是不準(zhǔn)的睬棚,但是它是以哪個(gè)精確度來作為“準(zhǔn)”的標(biāo)準(zhǔn)呢,我們?cè)囍鴣硖接懸幌隆?br>
環(huán)境:Xcode9解幼,模擬器iPhone7(iOS11)抑党,iPhone6(iOS10)
NSTimer
我們來寫一段代碼
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(logInfo) userInfo:nil repeats:YES];
}
}
- (void)logInfo {
NSLog(@"timer test");
}
好,跑一下
2017-11-10 09:12:32.566622+0800 QTimer[20276:7878806] timer test
2017-11-10 09:12:33.566811+0800 QTimer[20276:7878806] timer test
2017-11-10 09:12:34.566510+0800 QTimer[20276:7878806] timer test
2017-11-10 09:12:35.567532+0800 QTimer[20276:7878806] timer test
2017-11-10 09:12:36.567613+0800 QTimer[20276:7878806] timer test
2017-11-10 09:12:37.566615+0800 QTimer[20276:7878806] timer test
2017-11-10 09:12:38.567415+0800 QTimer[20276:7878806] timer test
2017-11-10 09:12:39.567650+0800 QTimer[20276:7878806] timer test
2017-11-10 09:12:40.566592+0800 QTimer[20276:7878806] timer test
可以看到撵摆,其計(jì)時(shí)偏差基本在1毫秒以內(nèi)底靠。
在正常的使用中,1毫秒以內(nèi)偏差的計(jì)時(shí)可以說是非常準(zhǔn)確了台汇,如果題目并不是需要實(shí)現(xiàn)納米級(jí)精度的計(jì)時(shí)苛骨,那么肯定是考慮到了其他影響到NSTimer計(jì)時(shí)精度的因素,我們?cè)囍鴣砜偨Y(jié)一下苟呐。
1痒芝、RunLoop的影響
為了驗(yàn)證,給計(jì)時(shí)任務(wù)加點(diǎn)重活
- (void)logInfo {
int count = 0;
for (int i = 0; i < 1000000; i++) {
count += i;
}
NSLog(@"timer test");
}
先在模擬器上跑
2017-11-10 09:35:33.413804+0800 QTimer[20503:7955660] timer test
2017-11-10 09:35:34.413108+0800 QTimer[20503:7955660] timer test
2017-11-10 09:35:35.414460+0800 QTimer[20503:7955660] timer test
2017-11-10 09:35:36.414036+0800 QTimer[20503:7955660] timer test
2017-11-10 09:35:37.413990+0800 QTimer[20503:7955660] timer test
2017-11-10 09:35:38.413622+0800 QTimer[20503:7955660] timer test
可以看到計(jì)時(shí)偏差還是能控制在1毫秒以內(nèi)
我們把上面的代碼用真機(jī)(iPhone6)跑一下
2017-11-10 09:34:42.332293+0800 QTimer[9739:3329479] timer test
2017-11-10 09:34:43.324582+0800 QTimer[9739:3329479] timer test
2017-11-10 09:34:44.331287+0800 QTimer[9739:3329479] timer test
2017-11-10 09:34:45.333884+0800 QTimer[9739:3329479] timer test
2017-11-10 09:34:46.331684+0800 QTimer[9739:3329479] timer test
2017-11-10 09:34:47.334392+0800 QTimer[9739:3329479] timer test
2017-11-10 09:34:48.332235+0800 QTimer[9739:3329479] timer test
2017-11-10 09:34:49.333350+0800 QTimer[9739:3329479] timer test
可以看到計(jì)時(shí)偏差已經(jīng)超過1毫秒了牵素,說明CPU性能對(duì)定時(shí)器的精度影響是有的严衬,但這是根本原因嗎?
我們?cè)偌右稽c(diǎn)重活看看
- (void)logInfo {
int count = 0;
for (int i = 0; i < 1000000000; i++) {
count += i;
}
NSLog(@"timer test");
}
2017-11-10 09:40:38.194879+0800 QTimer[9749:3330951] timer test
2017-11-10 09:40:44.188463+0800 QTimer[9749:3330951] timer test
2017-11-10 09:40:50.172012+0800 QTimer[9749:3330951] timer test
2017-11-10 09:40:56.172139+0800 QTimer[9749:3330951] timer test
2017-11-10 09:41:02.179022+0800 QTimer[9749:3330951] timer test
2017-11-10 09:41:08.170254+0800 QTimer[9749:3330951] timer test
2017-11-10 09:41:14.169011+0800 QTimer[9749:3330951] timer test
my god ... 計(jì)時(shí)偏差已經(jīng)去到了6秒之多笆呆,顯然是有問題的
原因分析:
定時(shí)器被添加在主線程中请琳,由于定時(shí)器在一個(gè)RunLoop中被檢測(cè)一次粱挡,所以如果在這一次的RunLoop中做了耗時(shí)的操作,當(dāng)前RunLoop持續(xù)的時(shí)間超過了定時(shí)器的間隔時(shí)間俄精,那么下一次定時(shí)就被延后了询筏。
解決方法:
1、在子線程中創(chuàng)建timer竖慧,在主線程進(jìn)行定時(shí)任務(wù)的操作
2嫌套、在子線程中創(chuàng)建timer,在子線程中進(jìn)行定時(shí)任務(wù)的操作圾旨,需要UI操作時(shí)切換回主線程進(jìn)行操作
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"timer test");
}];
}
}
- (void)logInfo {
int count = 0;
for (int i = 0; i < 1000000000; i++) {
count += i;
}
NSLog(@"timer test");
}
2017-11-10 09:52:57.725870+0800 QTimer[9759:3334283] timer test
2017-11-10 09:52:58.725829+0800 QTimer[9759:3334283] timer test
2017-11-10 09:52:59.725822+0800 QTimer[9759:3334283] timer test
2017-11-10 09:53:00.725979+0800 QTimer[9759:3334283] timer test
2017-11-10 09:53:01.725827+0800 QTimer[9759:3334283] timer test
2017-11-10 09:53:02.725774+0800 QTimer[9759:3334283] timer test
2017-11-10 09:53:03.725831+0800 QTimer[9759:3334283] timer test
2踱讨、RunLoop模式的影響
為了驗(yàn)證,我們?cè)诋?dāng)前頁面上添加一個(gè)tableview砍的,在定時(shí)器運(yùn)行時(shí)痹筛,我們對(duì)tableview進(jìn)行滑動(dòng)操作,可以發(fā)現(xiàn)廓鞠,定時(shí)器并不會(huì)觸發(fā)下一次的定時(shí)任務(wù)帚稠。
原因分析:
主線程的RunLoop有兩種預(yù)設(shè)的模式,RunLoopDefaultMode和TrackingRunLoopMode诫惭。
當(dāng)定時(shí)器被添加到主線程中且無指定模式時(shí)翁锡,會(huì)被默認(rèn)添加到DefaultMode中蔓挖,一般情況下定時(shí)器會(huì)正常觸發(fā)定時(shí)任務(wù)夕土。但是當(dāng)用戶進(jìn)行UI交互操作時(shí)(比如滑動(dòng)tableview),主線程會(huì)切換到TrackingRunLoopMode瘟判,在此模式下定時(shí)器并不會(huì)被觸發(fā)怨绣。
解決方法:
添加定時(shí)器到主線程的CommonMode中或者子線程中
[[NSRunLoop mainRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
其他方式的Timer
1、納秒級(jí)精度的Timer
使用mach_absolute_time()來實(shí)現(xiàn)更高精度的定時(shí)器拷获。
iPhone上有這么一個(gè)均勻變化的東西來提供給我們作為時(shí)間參考篮撑,就是CPU的時(shí)鐘周期數(shù)(ticks)。
通過mach_absolute_time()獲取CPU已運(yùn)行的tick數(shù)量匆瓜。將tick數(shù)經(jīng)過轉(zhuǎn)換變成秒或者納秒赢笨,從而實(shí)現(xiàn)時(shí)間的計(jì)算。
以下代碼實(shí)現(xiàn)來源于網(wǎng)絡(luò):
#include <mach/mach.h>
#include <mach/mach_time.h>
static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MILLISEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MILLISEC;
static mach_timebase_info_data_t timebase_info;
static uint64_t nanos_to_abs(uint64_t nanos) {
return nanos * timebase_info.denom / timebase_info.numer;
}
void waitSeconds(int seconds) {
mach_timebase_info(&timebase_info);
uint64_t time_to_wait = nanos_to_abs(seconds * NANOS_PER_SEC);
uint64_t now = mach_absolute_time();
mach_wait_until(now + time_to_wait);
}
理論上這是iPhone上最精準(zhǔn)的定時(shí)器驮吱,可以達(dá)到納秒級(jí)別的精度茧妒,但是怎樣去驗(yàn)證呢?
由于日志的輸出需要消耗時(shí)間左冬,CPU線程之間的調(diào)度也需要消耗時(shí)間桐筏,所以無法從Log中輸出的系統(tǒng)時(shí)間來驗(yàn)證其更高的精度,根據(jù)我測(cè)試的系統(tǒng)時(shí)間來看拇砰,時(shí)間偏差也是在1毫秒以內(nèi)梅忌。
2狰腌、CADisplayLink
CADisplayLink是一個(gè)頻率能達(dá)到屏幕刷新率的定時(shí)器類。iPhone屏幕刷新頻率為60幀/秒牧氮,也就是說最小間隔可以達(dá)到1/60s琼腔。
基本使用:
CADisplayLink * displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(logInfo)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
3、GCD定時(shí)器
我們知道踱葛,RunLoop是dispatch_source_t實(shí)現(xiàn)的timer展姐,所以理論上來說,GCD定時(shí)器的精度比NSTimer只高不低剖毯。
基本使用:
NSTimeInterval interval = 1.0;
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), interval * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(_timer, ^{
NSLog(@"GCD timer test");
});
dispatch_resume(_timer);
總結(jié)
從結(jié)果看圾笨,NSTimer在其使用場(chǎng)景下足夠準(zhǔn)了,對(duì)于“不準(zhǔn)”更多是集中在對(duì)其錯(cuò)誤的使用方式上逊谋,只要我們足夠深入了解擂达,正確地使用,就能讓它“準(zhǔn)”胶滋。
實(shí)際上板鬓,蘋果也不推薦使用太高精度的定時(shí)器,對(duì)于NSTimer究恤,精度在50-100ms都是正常的俭令,如果我們需要足夠高精度地進(jìn)行計(jì)時(shí)失仁,比如統(tǒng)計(jì)APP啟動(dòng)時(shí)間收厨、一段任務(wù)代碼的運(yùn)行時(shí)間等等叛复,NSTimer不是一個(gè)好的選擇胰挑,mach_absolute_time()或者可以幫到你在抛,蘋果開發(fā)工具也帶有更專業(yè)的API或者插件提供給開發(fā)者剩彬。