日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

ios利用RunLoop原理實現去監控卡頓實例詳解_IOS

作者:奶茶大叔 ? 更新時間: 2022-11-03 編程語言

一、卡頓問題的幾種原因

復雜 UI 、圖文混排的繪制量過大;

在主線程上做網絡同步請求;

在主線程做大量的 IO 操作;

運算量過大,CPU 持續高占用;

死鎖和主子線程搶鎖。

二、監測卡頓的思路

監測FPS:

FPS 是一秒顯示的幀數,也就是一秒內畫面變化數量。如果按照動畫片來說,動畫片的 FPS 就是 24,是達不到 60 滿幀的。也就是說,對于動畫片來說,24 幀時雖然沒有 60 幀時流暢,但也已經是連貫的了,所以并不能說 24 幀時就算是卡住了。 由此可見,簡單地通過監視 FPS 是很難確定是否會出現卡頓問題了,所以我就果斷棄了通過監視 FPS 來監控卡頓的方案。

RunLoop:

通過監控 RunLoop 的狀態來判斷是否會出現卡頓。RunLoop原理這里就不再多說,主要說方法,首先明確loop的狀態有六個

typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
    kCFRunLoopEntry , // 進入 loop
    kCFRunLoopBeforeTimers , // 觸發 Timer 回調
    kCFRunLoopBeforeSources , // 觸發 Source0 回調
    kCFRunLoopBeforeWaiting , // 等待 mach_port 消息
    kCFRunLoopAfterWaiting ), // 接收 mach_port 消息
    kCFRunLoopExit , // 退出 loop
    kCFRunLoopAllActivities  // loop 所有狀態改變
}

我們需要監測的狀態有兩個:RunLoop 在進入睡眠之前和喚醒后的兩個 loop 狀態定義的值,分別是 kCFRunLoopBeforeSources 和 kCFRunLoopAfterWaiting ,也就是要觸發 Source0 回調和接收 mach_port 消息兩個狀態。

三、如何檢查卡頓

說下步驟:

創建一個 CFRunLoopObserverContext 觀察者;

將創建好的觀察者 runLoopObserver 添加到主線程 RunLoop 的 common 模式下觀察;

創建一個持續的子線程專門用來監控主線程的 RunLoop 狀態;

一旦發現進入睡眠前的 kCFRunLoopBeforeSources 狀態,或者喚醒后的狀態 kCFRunLoopAfterWaiting,在設置的時間閾值內一直沒有變化,即可判定為卡頓;

dump 出堆棧的信息,從而進一步分析出具體是哪個方法的執行時間過長;

上代碼:

#import <Foundation/Foundation.h>
@interface SMLagMonitor : NSObject
+ (instancetype)shareInstance;
- (void)beginMonitor; //開始監視卡頓
- (void)endMonitor;   //停止監視卡頓
@end
#import "SMLagMonitor.h"
#import "SMCallStack.h"
#import "SMCPUMonitor.h"
@interface SMLagMonitor() {
    int timeoutCount;
    CFRunLoopObserverRef runLoopObserver;
    @public
    dispatch_semaphore_t dispatchSemaphore;
    CFRunLoopActivity runLoopActivity;
}
@property (nonatomic, strong) NSTimer *cpuMonitorTimer;
@end
@implementation SMLagMonitor
#pragma mark - Interface
+ (instancetype)shareInstance {
    static id instance = nil;
    static dispatch_once_t dispatchOnce;
    dispatch_once(&dispatchOnce, ^{
        instance = [[self alloc] init];
    });
    return instance;
}
- (void)beginMonitor {
    //監測 CPU 消耗
    self.cpuMonitorTimer = [NSTimer scheduledTimerWithTimeInterval:3
                                                             target:self
                                                           selector:@selector(updateCPUInfo)
                                                           userInfo:nil
                                                            repeats:YES];
    //監測卡頓
    if (runLoopObserver) {
        return;
    }
    dispatchSemaphore = dispatch_semaphore_create(0); //Dispatch Semaphore保證同步
    //創建一個觀察者
    CFRunLoopObserverContext context = {0,(__bridge void*)self,NULL,NULL};
    runLoopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                              kCFRunLoopAllActivities,
                                              YES,
                                              0,
                                              &runLoopObserverCallBack,
                                              &context);
    //將觀察者添加到主線程runloop的common模式下的觀察中
    CFRunLoopAddObserver(CFRunLoopGetMain(), runLoopObserver, kCFRunLoopCommonModes);
    //創建子線程監控
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //子線程開啟一個持續的loop用來進行監控
        while (YES) {
            long semaphoreWait = dispatch_semaphore_wait(dispatchSemaphore, dispatch_time(DISPATCH_TIME_NOW, 20*NSEC_PER_MSEC));
            if (semaphoreWait != 0) {
                if (!runLoopObserver) {
                    timeoutCount = 0;
                    dispatchSemaphore = 0;
                    runLoopActivity = 0;
                    return;
                }
                //兩個runloop的狀態,BeforeSources和AfterWaiting這兩個狀態區間時間能夠檢測到是否卡頓
                if (runLoopActivity == kCFRunLoopBeforeSources || runLoopActivity == kCFRunLoopAfterWaiting) {
                    // 將堆棧信息上報服務器的代碼放到這里
                    //出現三次出結果
//                    if (++timeoutCount < 3) {
//                        continue;
//                    }
                    NSLog(@"monitor trigger");
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//                        [SMCallStack callStackWithType:SMCallStackTypeAll];
                    });
                } //end activity
            }// end semaphore wait
            timeoutCount = 0;
        }// end while
    });
}
- (void)endMonitor {
    [self.cpuMonitorTimer invalidate];
    if (!runLoopObserver) {
        return;
    }
    CFRunLoopRemoveObserver(CFRunLoopGetMain(), runLoopObserver, kCFRunLoopCommonModes);
    CFRelease(runLoopObserver);
    runLoopObserver = NULL;
}
#pragma mark - Private
static void runLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){
    SMLagMonitor *lagMonitor = (__bridge SMLagMonitor*)info;
    lagMonitor->runLoopActivity = activity;
    dispatch_semaphore_t semaphore = lagMonitor->dispatchSemaphore;
    dispatch_semaphore_signal(semaphore);
}
- (void)updateCPUInfo {
    thread_act_array_t threads;
    mach_msg_type_number_t threadCount = 0;
    const task_t thisTask = mach_task_self();
    kern_return_t kr = task_threads(thisTask, &threads, &threadCount);
    if (kr != KERN_SUCCESS) {
        return;
    }
    for (int i = 0; i < threadCount; i++) {
        thread_info_data_t threadInfo;
        thread_basic_info_t threadBaseInfo;
        mach_msg_type_number_t threadInfoCount = THREAD_INFO_MAX;
        if (thread_info((thread_act_t)threads[i], THREAD_BASIC_INFO, (thread_info_t)threadInfo, &threadInfoCount) == KERN_SUCCESS) {
            threadBaseInfo = (thread_basic_info_t)threadInfo;
            if (!(threadBaseInfo->flags & TH_FLAGS_IDLE)) {
                integer_t cpuUsage = threadBaseInfo->cpu_usage / 10;
                if (cpuUsage > 70) {
                    //cup 消耗大于 70 時打印和記錄堆棧
                    NSString *reStr = smStackOfThread(threads[i]);
                    //記錄數據庫中
//                    [[[SMLagDB shareInstance] increaseWithStackString:reStr] subscribeNext:^(id x) {}];
                    NSLog(@"CPU useage overload thread stack:\n%@",reStr);
                }
            }
        }
    }
}
@end

使用,直接在APP didFinishLaunchingWithOptions 方法里面這樣寫:

[[SMLagMonitor shareInstance] beginMonitor];

原文鏈接:https://www.jianshu.com/p/fa0c5a3746e8

欄目分類
最近更新