美文网首页程序员
一种优雅的卡顿检测方案

一种优雅的卡顿检测方案

作者: 果哥爸 | 来源:发表于2019-09-21 21:31 被阅读0次

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

    具体详见:FJFCatonDetectionTool

    一.卡顿检测

    1.主要变量介绍

    static CFRunLoopActivity _MainRunLoopActivity = 0;
    NSRunLoop *_monitorRunLoop;
    NSInteger _count;
    BOOL _checked;
    NSTimer *_monitorTimer;
    NSString *_dumpCatonString;
    
    • _MainRunLoopActivity: 记录主线程runloop当前状态

    • _monitorRunLoop: 监听线程runloop

    • _count:记录定时器回调卡顿次数,如果卡顿次数超过5次,也就是0.5秒,就认为卡顿

    • _checked:判断是否将需要执行的block注入主线程的runloop.

    • _dumpCatonString:当_count次数为3是输出堆栈日志信息,然后在超过5次,被认为卡顿的时候,比较两次堆栈日志内容,确定是否同一原因引起卡顿。

    2.主要思路分析:

    • 首先监听主线程的runloop回调,并用一个变量记录_MainRunLoopActivity记录当前主线程runloop的状态。
    - (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];
        }
    }
    
    • 同时开启一条线程,这条线程启动runloop进行保活,同时在当前线程runloop里面启动一个定时器,每隔0.1秒进行一次回调。
    - (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();
    }
    
    • 在定时器的回调里面判断当前主线程runloop状态_MainRunLoopActivity是否为kCFRunLoopBeforeWaiting,如果是kCFRunLoopBeforeWaiting(即将进入休眠),就将_count置为0,如果不是kCFRunLoopBeforeWaiting,就判断是否向主线程的runloop注入block已经回调,如果回调就执行block注入,如果没有回调就将_count++,并判断是否触发卡顿,如果_count等于3,将堆栈日志输出到_dumpCatonString,如果_count大于5,触发卡顿,就判断两次输出日志是否一致,如果一致说明是同一个原因引起。
    - (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.实现思路

    • 监听主线程runloop的状态回调状态,同时在主线程开启一个dispatch_source_t的定时器,每1秒回调一次
    - (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];
        }
    }
    
    • 然后在runloop处于kCFRunLoopAfterWaiting的时候,记录当前时间戳,在runloop处于kCFRunLoopBeforeWaiting的时候,算出两者时间差,如果时间差大于16.67毫秒,就用_MainRunLoopMillisecondPerSecond减去时间差,得出剩余时间.
    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);
        }
    }
    
    • 在定时器1秒的回调的时候,先去判断当前之间和之前记录时间戳差值是否大于16.67ms,如果大于,减去时间差值,然后将剩余时间转化为帧数,进行回调,然后将_MainRunLoopMillisecondPerSecond重置为1000ms.
    - (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

    最后

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

    相关文章

      网友评论

        本文标题:一种优雅的卡顿检测方案

        本文链接:https://www.haomeiwen.com/subject/zooluctx.html