iOS之精确定时器
今天看到一个有意思的问题:NStimer准吗?如果不准该怎样实现一个精确的NSTimer?
既然这样问了,那从题目的角度出发,NSTimer肯定是不准的,但是它是以哪个精确度来作为“准”的标准呢,我们试着来探讨一下。
环境:Xcode9,模拟器iPhone7(iOS11),iPhone6(iOS10)
NSTimer
我们来写一段代码
1
2
3
4
5
6
7
8
|
- ( 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" ); }</uitouch *> |
好,跑一下
1
2
3
4
5
6
7
8
9
|
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 |
可以看到,其计时偏差基本在1毫秒以内。
在正常的使用中,1毫秒以内偏差的计时可以说是非常准确了,如果题目并不是需要实现纳米级精度的计时,那么肯定是考虑到了其他影响到NSTimer计时精度的因素,我们试着来总结一下。
1、RunLoop的影响
为了验证,给计时任务加点重活
1
2
3
4
5
6
7
|
- ( void )logInfo { int count = 0 ; for ( int i = 0 ; i < 1000000 ; i++) { count += i; } NSLog(@ "timer test" ); } |
先在模拟器上跑
1
2
3
4
5
6
|
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 |
可以看到计时偏差还是能控制在1毫秒以内
我们把上面的代码用真机(iPhone6)跑一下
1
2
3
4
5
6
7
8
|
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 |
可以看到计时偏差已经超过1毫秒了,说明CPU性能对定时器的精度影响是有的,但这是根本原因吗?
我们再加一点重活看看
1
2
3
4
5
6
7
|
- ( void )logInfo { int count = 0 ; for ( int i = 0 ; i < 1000000000 ; i++) { count += i; } NSLog(@ "timer test" ); } |
1
2
3
4
5
6
7
|
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 ... 计时偏差已经去到了6秒之多,显然是有问题的
原因分析:
定时器被添加在主线程中,由于定时器在一个RunLoop中被检测一次,所以如果在这一次的RunLoop中做了耗时的操作,当前RunLoop持续的时间超过了定时器的间隔时间,那么下一次定时就被延后了。
解决方法:
-
在子线程中创建timer,在主线程进行定时任务的操作
-
在子线程中创建timer,在子线程中进行定时任务的操作,需要UI操作时切换回主线程进行操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
- ( 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" ); }</uitouch *> |
1
2
3
4
5
6
7
|
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模式的影响
为了验证,我们在当前页面上添加一个tableview,在定时器运行时,我们对tableview进行滑动操作,可以发现,定时器并不会触发下一次的定时任务。
原因分析:
主线程的RunLoop有两种预设的模式,RunLoopDefaultMode和TrackingRunLoopMode。
当定时器被添加到主线程中且无指定模式时,会被默认添加到DefaultMode中,一般情况下定时器会正常触发定时任务。但是当用户进行UI交互操作时(比如滑动tableview),主线程会切换到TrackingRunLoopMode,在此模式下定时器并不会被触发。
解决方法:
添加定时器到主线程的CommonMode中或者子线程中
[[NSRunLoop mainRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
其他方式的Timer
1、纳秒级精度的Timer
使用mach_absolute_time()来实现更高精度的定时器。
iPhone上有这么一个均匀变化的东西来提供给我们作为时间参考,就是CPU的时钟周期数(ticks)。
通过mach_absolute_time()获取CPU已运行的tick数量。将tick数经过转换变成秒或者纳秒,从而实现时间的计算。
以下代码实现来源于网络:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# 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); }</mach></mach> |
理论上这是iPhone上最精准的定时器,可以达到纳秒级别的精度,但是怎样去验证呢?
由于日志的输出需要消耗时间,CPU线程之间的调度也需要消耗时间,所以无法从Log中输出的系统时间来验证其更高的精度,根据我测试的系统时间来看,时间偏差也是在1毫秒以内。
2、CADisplayLink
CADisplayLink是一个频率能达到屏幕刷新率的定时器类。iPhone屏幕刷新频率为60帧/秒,也就是说最小间隔可以达到1/60s。
基本使用:
1
2
|
CADisplayLink * displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(logInfo)]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; |
3、GCD定时器
我们知道,RunLoop是dispatch_source_t实现的timer,所以理论上来说,GCD定时器的精度比NSTimer只高不低。
基本使用:
1
2
3
4
5
6
7
|
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); |
总结
从结果看,NSTimer在其使用场景下足够准了,对于“不准”更多是集中在对其错误的使用方式上,只要我们足够深入了解,正确地使用,就能让它“准”。
实际上,苹果也不推荐使用太高精度的定时器,对于NSTimer,精度在50-100ms都是正常的,如果我们需要足够高精度地进行计时,比如统计APP启动时间、一段任务代码的运行时间等等,NSTimer不是一个好的选择,mach_absolute_time()或者可以帮到你,苹果开发工具也带有更专业的API或者插件提供给开发者。