程序员

一种优雅的卡顿检测方案

2019-09-21  本文已影响0人  果哥爸

关于iOS的卡顿方案,网上很多文章都有阐述,这里说一下一种之前大表哥谈起的一种实现方式,这种方式算是挺优雅的。

具体详见:FJFCatonDetectionTool

一.卡顿检测

1.主要变量介绍

static CFRunLoopActivity _MainRunLoopActivity = 0;
NSRunLoop *_monitorRunLoop;
NSInteger _count;
BOOL _checked;
NSTimer *_monitorTimer;
NSString *_dumpCatonString;

2.主要思路分析:

- (void)startMonitor {
    if (!_monitorRunLoop) {
        CFRunLoopObserverContext context = { 0, nil, NULL, NULL };
        CFRunLoopObserverRef observer = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                                                kCFRunLoopAllActivities,
                                                                YES,
                                                                0,
                                                                &_MainRunLoopObserverCallBack,
                                                                &context);
        CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
        CFRelease(observer);
        [self startFpsTimer];
        [NSThread detachNewThreadSelector:@selector(monitorThreadStart) toTarget:self withObject:nil];
    }
}
- (void)monitorThreadStart {
    _monitorTimer = [NSTimer timerWithTimeInterval:1 / 10.f
                                             target:self
                                           selector:@selector(timerAction:)
                                           userInfo:nil
                                            repeats:YES];
    
    _monitorRunLoop = [NSRunLoop currentRunLoop];
    [_monitorRunLoop addTimer:_monitorTimer forMode:NSRunLoopCommonModes];
    
    CFRunLoopRun();
}
- (void)timerAction:(NSTimer *)timer {
    if (_MainRunLoopActivity != kCFRunLoopBeforeWaiting) {
        if (!_checked){
            _checked = YES;
            CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^{
                self->_checked = NO;
                self->_count = 0;
            });
        }
        else {
            ++_count;
            
            if (_count == 3) {
                _dumpCatonString = [BSBacktraceLogger bs_backtraceOfMainThread];
            }
            
            if (_count > 5) {
                _count = 0;
                NSLog(@"卡住啦");
                NSString *tmpCatonString = [BSBacktraceLogger bs_backtraceOfMainThread];
                if ([_dumpCatonString isEqualToString:tmpCatonString]) {
                    NSLog(@"%@", tmpCatonString);
                }
            }
        }
    }
    else{
        _count = 0;
    }
}

这里之所以对当前主线程runloop状态_MainRunLoopActivity是否为kCFRunLoopBeforeWaiting进行判断是因为向主线程runloop注入block,并不会唤醒处于休眠状态的主线程,只能等待runloop被唤醒之后,在runloop进入kCFRunLoopBeforeSourceskCFRunLoopAfterWaiting状态之后才会进行相关block处理。

runloop处理流程

二.FPS帧率计算

现阶段,常用的FPS监控基本都是居于CADisplayLink来实现的。
因为CADisplayLink信号发射频率和屏幕的刷新频率一致,固定是1秒钟60次,也就是16.67毫秒一次,因此常用一个计数器来统计每一秒钟,进行了多少次回调,来算出当前FPS

CADisplayLink有一个缺点,一旦启用了CADisplayLink定时器,就算将frameInterval(iOS10之前)preferredFramesPerSecond(iOS之后)设置为100,信号的发射频率依然是1秒钟60次,这样就会使得runloop处于活跃的状态。这样不仅会损耗大量的CPU资源,还会影响目标runLoop处理其它事件源。

这里我们用另外一种方法来统计FPS的帧率:

主要思路:记录主线程runloopkCFRunLoopAfterWaiting的时间戳,然后在kCFRunLoopBeforeWaiting的时候算出两者的时间差,如果时间差大于16.67ms,就用1000ms减去时间差,然后启动定时器,每隔1秒回调一次,这时候将剩下的时间除以一帧的时间16.67ms,算出帧数,进行回调。

A.辅助变量

/// 主线程 runloop 唤醒状态 时间
static u_int64_t _MainRunLoopAfterWaitingStatusTime = 0;
//  一秒钟 为 10000毫秒
static float _MainRunLoopMillisecondPerSecond = 1000.0;
// 每一帧 时间 回调为 16.67
static double _MainRunLoopBlanceMillisecondPerFrame = 16.666666;

B.实现思路

- (void)startMonitor {
    if (!_monitorRunLoop) {
        CFRunLoopObserverContext context = { 0, nil, NULL, NULL };
        CFRunLoopObserverRef observer = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                                                kCFRunLoopAllActivities,
                                                                YES,
                                                                0,
                                                                &_MainRunLoopObserverCallBack,
                                                                &context);
        CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
        CFRelease(observer);
        [self startFpsTimer];
        [NSThread detachNewThreadSelector:@selector(monitorThreadStart) toTarget:self withObject:nil];
    }
}
static mach_timebase_info_data_t _MainRunLoopFrameTimeBase(void) {
    static mach_timebase_info_data_t *timebase = 0;
    
    if (!timebase) {
        timebase = malloc(sizeof(mach_timebase_info_data_t));
        mach_timebase_info(timebase);
    }
    return *timebase;
}

static void _MainRunLoopTimeDifference(){
    mach_timebase_info_data_t timebase = _MainRunLoopFrameTimeBase();
    u_int64_t check = mach_absolute_time();
    u_int64_t sum = (check - _MainRunLoopAfterWaitingStatusTime) * (double)timebase.numer / (double)timebase.denom / 1e6;
    _MainRunLoopAfterWaitingStatusTime = check;
    if (sum > _MainRunLoopBlanceMillisecondPerFrame) {
        NSInteger blanceFramePerSecond = (NSInteger)(_MainRunLoopMillisecondPerSecond - sum);
        _MainRunLoopMillisecondPerSecond = (blanceFramePerSecond > 0) ? blanceFramePerSecond : 0;
        NSLog(@"sum: %lld", sum);
        NSLog(@"_MainRunLoopMillisecondPerSecond = %ld", (long)_MainRunLoopMillisecondPerSecond);
    }
}

static void _MainRunLoopFrameCallBack(CFRunLoopActivity activity) {
    if (activity == kCFRunLoopAfterWaiting){
        _MainRunLoopAfterWaitingStatusTime = mach_absolute_time();
    }
    else {
        _MainRunLoopTimeDifference();
    }
}

static void _MainRunLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
    _MainRunLoopActivity = activity;

    if (_MainRunLoopActivity == kCFRunLoopBeforeWaiting ||
        _MainRunLoopActivity == kCFRunLoopAfterWaiting) {
        _MainRunLoopFrameCallBack(activity);
    }
}
- (void)startFpsTimer {
    
    _gcdTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    
    dispatch_source_set_timer(_gcdTimer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
    
    dispatch_source_set_event_handler(_gcdTimer, ^{
        _MainRunLoopTimeDifference();
        NSInteger fps = (NSInteger)(_MainRunLoopMillisecondPerSecond/_MainRunLoopBlanceMillisecondPerFrame);
        if (self.fpsBlock) {
            self.fpsBlock(fps);
        }

        _MainRunLoopMillisecondPerSecond = 1000.0;
    });
    dispatch_resume(_gcdTimer);
}

以上是主要的实现逻辑,具体详见:

FJFCatonDetectionTool

最后

如果大家有什么疑问或者意见向左的地方,欢迎大家留言讨论。

上一篇 下一篇

猜你喜欢

热点阅读