美文网首页
iOS Runloop进行卡顿检测代码

iOS Runloop进行卡顿检测代码

作者: 江湖闹士 | 来源:发表于2023-08-29 11:56 被阅读0次

    代码参考:

    #import <Foundation/Foundation.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface Monitor : NSObject
    + (instancetype)shareInstance;
    - (void)startMonitor;
    @end
    
    NS_ASSUME_NONNULL_END
    
    #import "Monitor.h"
    
    @interface Monitor()
    
    @property (nonatomic,strong) NSThread *monitorThread;
    @property (nonatomic,strong) NSDate *startDate;
    @property (nonatomic,assign, getter=isExcuting) BOOL excuting;//是否正在执行任务
    @end
    
    
    @implementation Monitor {
        CFRunLoopObserverRef _observer;//观察者
        CFRunLoopTimerRef _timer;//定时器
    }
    
    + (instancetype)shareInstance {
        
        static dispatch_once_t once_token;
        static Monitor *monitor;
        dispatch_once(&once_token, ^{
            if (!monitor) {
                monitor = [[Monitor alloc] init];
                monitor.monitorThread = [[NSThread alloc] initWithTarget:self selector:@selector(monitorThreadEntrypoint) object:nil];
                [monitor.monitorThread start];
            }
        });
        return monitor;
    }
    
    //创建一个子线程,在线程启动时,启动其 Runloop
    + (void)monitorThreadEntrypoint {
        
        @autoreleasepool {
            [[NSThread currentThread] setName:@"minotor"];
            
            [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
            [[NSRunLoop currentRunLoop] run];
        }
    }
    
    //2 检测卡顿方法
    - (void)startMonitor {
        if(_observer) {
            return;
        }
        //创建 observer
        CFRunLoopObserverContext context = {0,(__bridge void *)self, NULL, NULL, NULL};
        _observer = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, &runloopObserverCallBack, &context);
        //将 observer 添加到主线程的 Runloop 中
        CFRunLoopAddObserver(CFRunLoopGetMain(), _observer, kCFRunLoopCommonModes);
        
        //创建一个 Timer,并添加到子线程的 Runloop 中
        [self performSelector:@selector(addTimerToMonitorThread) onThread:self.monitorThread withObject:nil waitUntilDone:NO modes:@[NSRunLoopCommonModes]];
        
    }
    
    
    /// observer 回调
    /// 因为主线程中的 block、交互事件、以及其他任务都是在 KCFRunLoopBeforeSources 到 KCFRunLoopBeforeWaiting 之前执行
    /// 所以在开始执行 sources 时 ,即 KCFRunLoopBeforeSources 状态时,记录一下时间,并把正在执行任务的标记设置为 yes
    /// 将要进入睡眠状态时,即 KCFRunLoopBeforeWaiting 状态时,将正在执行任务的标记设置为 NO
    static void runloopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
        Monitor *monitor = (__bridge Monitor *)info;
        switch (activity) {
            case kCFRunLoopEntry:
                NSLog(@"kCFRunLoopEntry");
                break;
            case kCFRunLoopBeforeSources:
                NSLog(@"kCFRunLoopBeforeSources");
                monitor.startDate = [NSDate date];
                monitor.excuting = YES;
                break;
            case kCFRunLoopBeforeTimers:
                NSLog(@"kCFRunLoopBeforeTimers");
                break;
            case kCFRunLoopBeforeWaiting:
                NSLog(@"kCFRunLoopBeforeWaiting");
                monitor.excuting = NO;
                break;
            case kCFRunLoopAfterWaiting:
                NSLog(@"kCFRunLoopAfterWaiting");
                break;
            case kCFRunLoopExit:
                NSLog(@"kCFRunLoopExit");
                break;
            case kCFRunLoopAllActivities:
                NSLog(@"kCFRunLoopAllActivities");
                break;
        }
    }
    
    ///添加定时器到 Runloop 中
    - (void)addTimerToMonitorThread {
        
        if (_timer) return;
        
        //创建一个 Timer
        CFRunLoopRef currentRunLoop = CFRunLoopGetCurrent();
        CFRunLoopTimerContext context = {0, (__bridge void *)self, NULL, NULL, NULL};
        
        _timer = CFRunLoopTimerCreate(kCFAllocatorDefault, 0.01, 0.01, 0, 0, &runLoopTimerCallBack, &context);
        
        //添加到子线程的 Runloop 中
        CFRunLoopAddTimer(currentRunLoop, _timer, kCFRunLoopCommonModes);
    }
    
    static void runLoopTimerCallBack(CFRunLoopTimerRef timer, void *info) {
        Monitor *monitor = (__bridge Monitor *)info;
        if (!monitor.isExcuting){//即 Runloop 已经进入休眠,kCFRunLoopBeforeWaiting 状态
            return;
        }
        
        //如果主线程正在执行任务,并且这一次 loop 执行到现在还没有执行完,那就需要计算时间差
        //即从 kCFRunLoopBeforeSources 状态到当前状态的时间差 excuteTime
        NSTimeInterval excuteTime = [[NSDate date] timeIntervalSinceDate:monitor.startDate];
        NSLog(@"定时器:当前线程:%@,主线程执行时间:%f秒",[NSThread currentThread],excuteTime);
        //Timer每 0.1s 执行一次,如果当前正在执行任务的状态为 YES,并且从开始执行到现在的时间大于阈值,则把堆栈信息保存起来,便于后面处理
        if (excuteTime >= 0.01) {
            NSLog(@"线程卡顿了%f秒",excuteTime);
            [monitor handleStackInfo];
        }
    }
    
    //堆栈信息处理
    - (void)handleStackInfo {
        //使用第三方CrashReporter 或者其他来打印出堆栈信息
    }
    @end
    

    相关文章

      网友评论

          本文标题:iOS Runloop进行卡顿检测代码

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