NSTimer
大家都知道NSTimer不准,那到底是怎么个不准法,其原因是啥呢? 先上代码:
- (void)viewDidLoad {
[super viewDidLoad];
[self initTimer]; //这个函数里去初始化timer。
}
-(void)initTimer{
NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"ddd");
}];
[[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
[timer fire];
}
2020-07-18 22:01:14.676404+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:15.508842+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:16.508356+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:17.509282+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:18.509263+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:19.509406+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:20.508536+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:21.509202+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:22.508868+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:23.509636+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:24.509635+0800 testMySort[97584:6739614] ddd
这是普通的创建timer,然后隔1s去输出打印的效果,可以看到,其计时偏差基本在1毫秒以内。在正常的使用中,1毫秒以内偏差的计时可以说是非常准确了,基本是能够满足绝大部分的需求常见的。
1、RunLoop的影响
从上面的代码可以看出,timer被初始化后是加入到主线程的runloop中的,那么runloop是否是到账NSTimer不准确的原因呢?为了验证,给计时任务加点重活。
- (void)viewDidLoad {
[super viewDidLoad];
[self initTimer]; //这个函数里去初始化timer。
// 给主线程增加一些计算繁重的任务
int count = 0;
for (int i = 0; i < 1000000000; i++) {
count += i;
}
NSLog(@"timer test");
}
2020-07-18 22:01:11.508069+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:14.651825+0800 testMySort[97584:6739614] timer test
2020-07-18 22:01:14.676404+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:15.508842+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:16.508356+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:17.509282+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:18.509263+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:19.509406+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:20.508536+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:21.509202+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:22.508868+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:23.509636+0800 testMySort[97584:6739614] ddd
2020-07-18 22:01:24.509635+0800 testMySort[97584:6739614] ddd
可以看出,当在一个runloop循环间cpu有大量的计算任务的时候,timer就变得不准了(第1个打印ddd和第2个打印ddd间相差了3s)。
原因分析:
定时器被添加在主线程中,由于定时器在一个RunLoop中被检测一次,所以如果在这一次的RunLoop中做了耗时的操作,当前RunLoop持续的时间超过了定时器的间隔时间,那么下一次定时就被延后了。
解决方法:
在子线程中创建timer,在子线程中进行定时任务的操作,需要UI操作时切换回主线程进行操作
-(void) initTimer{
NSThread* thread = [[NSThread alloc]initWithBlock:^{
NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"ddd");
}];
[timer fire];
[[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
[[NSRunLoop currentRunLoop]run];
}];
[thread start];
}
2020-07-18 22:14:45.473855+0800 testMySort[97978:6762790] ddd
2020-07-18 22:14:46.478074+0800 testMySort[97978:6762790] ddd
2020-07-18 22:14:47.478109+0800 testMySort[97978:6762790] ddd
2020-07-18 22:14:48.478181+0800 testMySort[97978:6762790] ddd
2020-07-18 22:14:48.819898+0800 testMySort[97978:6762615] timer test
2020-07-18 22:14:49.478246+0800 testMySort[97978:6762790] ddd
2020-07-18 22:14:50.478134+0800 testMySort[97978:6762790] ddd
2020-07-18 22:14:51.478131+0800 testMySort[97978:6762790] ddd
2020-07-18 22:14:52.478157+0800 testMySort[97978:6762790] ddd
2020-07-18 22:14:53.478236+0800 testMySort[97978:6762790] ddd
2020-07-18 22:14:54.479399+0800 testMySort[97978:6762790] ddd
2020-07-18 22:14:55.478285+0800 testMySort[97978:6762790] ddd
从上面的打印的时间可以看出,即便主线程有其他耗时或繁重的计算,也不会影响timer。
2、RunLoop模式的影响
为了验证,我们在当前页面上添加一个tableview,在定时器运行时,我们对tableview进行滑动操作,可以发现,定时器并不会触发下一次的定时任务。
原因分析:
主线程的RunLoop有两种预设的模式,RunLoopDefaultMode和TrackingRunLoopMode。
当定时器被添加到主线程中且无指定模式时,会被默认添加到DefaultMode中,一般情况下定时器会正常触发定时任务。但是当用户进行UI交互操作时(比如滑动tableview),主线程会切换到TrackingRunLoopMode,在此模式下定时器并不会被触发。
解决方法:
添加定时器到主线程的CommonMode中或者子线程中。
其他方式的Timer
1、纳秒级精度的Timer
使用mach_absolute_time()来实现更高精度的定时器。
iPhone上有这么一个均匀变化的东西来提供给我们作为时间参考,就是CPU的时钟周期数(ticks)。
通过mach_absolute_time()获取CPU已运行的tick数量。将tick数经过转换变成秒或者纳秒,从而实现时间的计算。
#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上最精准的定时器,可以达到纳秒级别的精度,但是怎样去验证呢?
由于日志的输出需要消耗时间,CPU线程之间的调度也需要消耗时间,所以无法从Log中输出的系统时间来验证其更高的精度,根据我测试的系统时间来看,时间偏差也是在1毫秒以内。
2、GCD定时器
我们知道,RunLoop是dispatch_source_t实现的timer,所以理论上来说,GCD定时器的精度比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);
总结
从结果看,NSTimer在其使用场景下足够准了,对于“不准”更多是集中在对其错误的使用方式上,只要我们足够深入了解,正确地使用,就能让它“准”。
实际上,苹果也不推荐使用太高精度的定时器,对于NSTimer,精度在50-100ms都是正常的,如果我们需要足够高精度地进行计时,比如统计APP启动时间、一段任务代码的运行时间等等,NSTimer不是一个好的选择,mach_absolute_time()或者可以帮到你,苹果开发工具也带有更专业的API或者插件提供给开发者。
网友评论