iOS-卡顿简单监测三(NSTimer 实现+附实例)

序言

之前写了两篇文章介绍如何检测卡顿

iOS实时卡顿检测-RunLoop(附实例)这是借助于信号量Semaphore来实现的。

iOS-卡顿简单监测二(NSTimer 实现+附实例),借助定时器实现。

本介绍第三种方法,采用定时器 NSTimer实现,原理方面的就不多说了,看之前两篇文章即可,直接上代码。

一 实现原理

先看官方文档中关于RunLoop的执行顺序介绍

1. Notify observers that the run loop has been entered.
2. Notify observers that any ready timers are about to fire.
3. Notify observers that any input sources that are not port based are about to fire.
4. Fire any non-port-based input sources that are ready to fire.
5. If a port-based input source is ready and waiting to fire, process the event immediately. Go to step 9.
6. Notify observers that the thread is about to sleep.
7. Put the thread to sleep until one of the following events occurs:
 * An event arrives for a port-based input source.
 * A timer fires.
 * The timeout value set for the run loop expires.
 * The run loop is explicitly woken up.
8. Notify observers that the thread just woke up.
9. Process the pending event.
 * If a user-defined timer fired, process the timer event and restart the loop. Go to step 2.
 * If an input source fired, deliver the event.
 * If the run loop was explicitly woken up but has not yet timed out, restart the loop. Go to step 2.
10. Notify observers that the run loop has exited.
  • 用伪代码来实现就是这样的:
{
    /// 1. 通知Observers,即将进入RunLoop
    /// 此处有Observer会创建AutoreleasePool: _objc_autoreleasePoolPush();
    __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopEntry);
    do {
 
        /// 2. 通知 Observers: 即将触发 Timer 回调。
        __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopBeforeTimers);
        /// 3. 通知 Observers: 即将触发 Source (非基于port的,Source0) 回调。
        __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopBeforeSources);
        __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__(block);
 
        /// 4. 触发 Source0 (非基于port的) 回调。
        __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__(source0);
        __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__(block);
 
        /// 6. 通知Observers,即将进入休眠
        /// 此处有Observer释放并新建AutoreleasePool: _objc_autoreleasePoolPop(); _objc_autoreleasePoolPush();
        __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopBeforeWaiting);
 
        /// 7. sleep to wait msg.
        mach_msg() -> mach_msg_trap();
        
 
        /// 8. 通知Observers,线程被唤醒
        __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopAfterWaiting);
 
        /// 9. 如果是被Timer唤醒的,回调Timer
        __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__(timer);
 
        /// 9. 如果是被dispatch唤醒的,执行所有调用 dispatch_async 等方法放入main queue 的 block
        __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(dispatched_block);
 
        /// 9. 如果如果Runloop是被 Source1 (基于port的) 的事件唤醒了,处理这个事件
        __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__(source1);
 
 
    } while (...);
 
    /// 10. 通知Observers,即将退出RunLoop
    /// 此处有Observer释放AutoreleasePool: _objc_autoreleasePoolPop();
    __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopExit);
}

主线程的RunLoop是在应用启动时自动开启的,也没有超时时间,所以正常情况下,主线程的RunLoop 只会在 步骤2步骤9 之间无限循环下去。

那么,我们只需要在主线程RunLoop中添加一个observer,检测从kCFRunLoopBeforeSourceskCFRunLoopBeforeWaiting 花费的时间 是否过长。如果花费的时间大于某一个阙值,我们就认为有卡顿,并把当前的线程堆栈转储到文件中,并在以后某个合适的时间,将卡顿信息文件上传到服务器。

二 实现步骤如下
2.1 创建一个子线程,在线程启动时,开启其Runloop

属性及成员变量声明

@interface Monitor()
/** thread */
@property(nonatomic, strong)NSThread *monitorThread;
/** startDate */
@property(nonatomic, strong)NSDate *startDate;
/** excuting */
@property(nonatomic, assign, getter=isExcuting)BOOL excuting;  // 是否正在执行任务
@end

@implementation Monitor {
    CFRunLoopObserverRef _observer;  // observer
    CFRunLoopTimerRef _timer; // 定时器
}

创建子线程

/** 单例 */
+ (instancetype)shareInstance {
    static Monitor *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        instance.monitorThread = [[NSThread alloc] initWithTarget:self selector:@selector(monitorThreadEntryPoint) object:nil];
        [instance.monitorThread start];
    });
    return instance;
}

/// 创建一个子线程,在线程启动时,启动其RunLoop
+ (void)monitorThreadEntryPoint {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"Monitor"];
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [runLoop run];
    }
}
2.2 往主线程的 RunLoop中添加 observer,并且在子线程中添加一个定时器
// 第二步,在开始监测时,往主线程的RunLoop中添加一个observer,并往子线程中添加一个定时器,每0.1秒检测一次耗时的时长。
- (void)startMonitor {
    if (_observer) {
        return;
    }
    // 1.创建 observer
    CFRunLoopObserverContext context = {0,(__bridge void*)self, NULL, NULL, NULL};
    _observer = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                        kCFRunLoopAllActivities,
                                        YES,
                                        0,
                                        &runLoopObserverCallBack,
                                        &context);
    // 2.将 observer 添加到住线程的 runloop 中
    CFRunLoopAddObserver(CFRunLoopGetMain(), _observer, kCFRunLoopCommonModes);
    // 3.创建一个 timer,并添加到子线程的 runloop 中
    [self performSelector:@selector(addTimerToMonitorThread) onThread:self.monitorThread withObject:nil waitUntilDone:NO modes:@[NSRunLoopCommonModes]];
}

添加定时器及检测方法

/// 添加定时器到 runloop 中
- (void)addTimerToMonitorThread {
    if (_timer) {
        return;
    }
    // 创建一个 timer
    CFRunLoopRef currentRunLoop = CFRunLoopGetCurrent();
    CFRunLoopTimerContext context = {0, (__bridge void*)self, NULL, NULL, NULL};
    
    _timer = CFRunLoopTimerCreate(kCFAllocatorDefault,
                                  0.1,
                                  0.1,
                                  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);
    
    // Time 每 0.01S执行一次,如果当前正在执行任务的状态为YES,并且从开始执行到现在的时间大于阙值,则把堆栈信息保存下来,便于后面处理。
    // 为了能够捕获到堆栈信息,我把timer的间隔调的很小(0.01),而评定为卡顿的阙值也调的很小(0.01)
    if (excuteTime >= 0.01) {
        NSLog(@"线程卡顿了%f 秒",excuteTime);
        [monitor handleStackInfo];
    }
}

如果monitor.isExcuting == NO,表示runloop即将进入睡眠,直接 pass,不做判断。变量excuteTimerunloop从进入kCFRunLoopBeforeSources到当前的时间间隔,即做了很多事情,如果这个值大于某个阙值,则可以认为发生了卡顿,记录堆栈信息即可。

2.3 RunLoop的observer回调

/** observer 回调
 1.因为主线程中的 block,交互事件,以及其他任务都是在 kCFRunLoopBeforeSources到kCFRunLoopBeforeWaiting之前执行.
 2.所以在开始执行Sources时,即kCFRunLoopBeforeSources状态时,记录一下时间,并把正在执行任务的标记设置为 YES.
 3.将要进入睡眠状态时,即kCFRunLoopBeforeWaiting状态时,将正在执行任务的标记设置为 NO.
 */
static void runLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
    Monitor *monitor = (__bridge Monitor *)info;
    switch (activity) {
        case kCFRunLoopEntry:
            NSLog(@"kCFRunLoopEntry");
            break;
        case kCFRunLoopBeforeTimers:
            NSLog(@"kCFRunLoopBeforeTimers");
            break;
        case kCFRunLoopBeforeSources:
            NSLog(@"kCFRunLoopBeforeSources");
            monitor.startDate = [NSDate date];
            monitor.excuting = YES;
            break;
        case kCFRunLoopBeforeWaiting:
            NSLog(@"kCFRunLoopBeforeWaiting");
            monitor.excuting = NO;
            break;
        case kCFRunLoopAfterWaiting:
            NSLog(@"kCFRunLoopAfterWaiting");
            break;
        case kCFRunLoopExit:
            NSLog(@"kCFRunLoopExit");
            break;
        default:
            break;
    }
}

因为主线程中的 block,交互事件,以及其他任务都是在 kCFRunLoopBeforeSourceskCFRunLoopBeforeWaiting之前执行。

所以在开始执行Sources时,即kCFRunLoopBeforeSources状态时,记录一下时间,并把正在执行任务的标记设置为 YES,将要进入睡眠状态时,即kCFRunLoopBeforeWaiting状态时,将正在执行任务的标记设置为 NO

2.4 获取堆栈信息

借助 PLCrashReporter来获取所有线程对线信息。

- (void)handleStackInfo {
    PLCrashReporterConfig *config = [[PLCrashReporterConfig alloc] initWithSignalHandlerType:PLCrashReporterSignalHandlerTypeBSD symbolicationStrategy:PLCrashReporterSymbolicationStrategyAll];
    
    PLCrashReporter *crashReporter = [[PLCrashReporter alloc] initWithConfiguration:config];
    
    NSData *data = [crashReporter generateLiveReport];
    PLCrashReport *reporter = [[PLCrashReport alloc] initWithData:data error:NULL];
    NSString *report = [PLCrashReportTextFormatter stringValueForCrashReport:reporter withTextFormat:PLCrashReportTextFormatiOS];
    
    NSLog(@"---------卡顿信息\n%@\n--------------",report);
}
三 执行结果
  • runloop状态发生变化
2019-07-04 20:05:10.352081+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeTimers
2019-07-04 20:05:10.352227+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeSources
2019-07-04 20:05:10.352429+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeTimers
2019-07-04 20:05:10.352520+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeSources
2019-07-04 20:05:10.352691+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeTimers
2019-07-04 20:05:10.352839+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeSources
2019-07-04 20:05:10.353456+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeTimers
2019-07-04 20:05:10.353554+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeSources
2019-07-04 20:05:10.353662+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeTimers
2019-07-04 20:05:10.353742+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeSources
2019-07-04 20:05:10.353874+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeTimers
2019-07-04 20:05:10.353966+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeSources
  • 发生卡顿了
2019-07-04 20:05:10.353874+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeTimers
2019-07-04 20:05:10.353966+0800 MonitorTime2[31573:3915508] kCFRunLoopBeforeSources
2019-07-04 20:05:10.463677+0800 MonitorTime2[31573:3915677] 定时器: 当前线程:{number = 4, name = Monitor},主线程执行时间:0.109427秒
2019-07-04 20:05:10.464029+0800 MonitorTime2[31573:3915677] 线程卡顿了0.109427 秒
  • 获取堆栈信息
2019-07-04 20:05:12.737483+0800 MonitorTime2[31573:3915677] ---------卡顿信息
Incident Identifier: 43B0E0A0-7CAC-401C-BE54-25DE1A4B4750
CrashReporter Key:   TODO
Hardware Model:      x86_64
Process:         MonitorTime2 [31573]
Path:            /Users/cs/Library/Developer/CoreSimulator/Devices/A54D352A-B4C5-4A1A-8419-BA77AEEB6936/data/Containers/Bundle/Application/5A1CF5A8-E858-4B32-9EE7-080B6535C923/MonitorTime2.app/MonitorTime2
Identifier:      cs.MonitorTime2
Version:         1.0 (1)
Code Type:       X86-64
Parent Process:  debugserver [31574]

Date/Time:       2019-07-04 12:05:10 +0000
OS Version:      Mac OS X 12.2 (18F132)
Report Version:  104

Exception Type:  SIGTRAP
Exception Codes: TRAP_TRACE at 0x1045ea17f
Crashed Thread:  9

Thread 0:
0   libsystem_kernel.dylib              0x000000010755c7be writev + 10
1   libsystem_trace.dylib               0x00000001074cd0e5 _os_log_impl_mirror_to_stderr + 486
2   libsystem_trace.dylib               0x00000001074cc919 _os_log_impl_flatten_and_send + 6635
3   libsystem_trace.dylib               0x00000001074cdd80 _

本文参考 RunLoop总结:RunLoop的应用场景(四)App卡顿监测


相关文章参考

  • iOS-卡顿简单监测二(NSTimer 实现+附实例)
  • iOS实时卡顿检测-RunLoop(附实例)

  • 监控卡顿的方法 (使用RunLoop监测卡顿的片段代码)
  • 简单监测iOS卡顿的demo (使用RunLoop监测卡顿的例子)

项目链接地址 - MonitorTime2

你可能感兴趣的:(iOS-卡顿简单监测三(NSTimer 实现+附实例))