ios利用RunLoop原理實(shí)現(xiàn)去監(jiān)控卡頓實(shí)例詳解
一、卡頓問題的幾種原因
復(fù)雜 UI 、圖文混排的繪制量過大;
在主線程上做網(wǎng)絡(luò)同步請(qǐng)求;
在主線程做大量的 IO 操作;
運(yùn)算量過大,CPU 持續(xù)高占用;
死鎖和主子線程搶鎖。
二、監(jiān)測(cè)卡頓的思路
監(jiān)測(cè)FPS:
FPS 是一秒顯示的幀數(shù),也就是一秒內(nèi)畫面變化數(shù)量。如果按照動(dòng)畫片來說,動(dòng)畫片的 FPS 就是 24,是達(dá)不到 60 滿幀的。也就是說,對(duì)于動(dòng)畫片來說,24 幀時(shí)雖然沒有 60 幀時(shí)流暢,但也已經(jīng)是連貫的了,所以并不能說 24 幀時(shí)就算是卡住了。 由此可見,簡(jiǎn)單地通過監(jiān)視 FPS 是很難確定是否會(huì)出現(xiàn)卡頓問題了,所以我就果斷棄了通過監(jiān)視 FPS 來監(jiān)控卡頓的方案。
RunLoop:
通過監(jiān)控 RunLoop 的狀態(tài)來判斷是否會(huì)出現(xiàn)卡頓。RunLoop原理這里就不再多說,主要說方法,首先明確loop的狀態(tài)有六個(gè)
typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) { kCFRunLoopEntry , // 進(jìn)入 loop kCFRunLoopBeforeTimers , // 觸發(fā) Timer 回調(diào) kCFRunLoopBeforeSources , // 觸發(fā) Source0 回調(diào) kCFRunLoopBeforeWaiting , // 等待 mach_port 消息 kCFRunLoopAfterWaiting ), // 接收 mach_port 消息 kCFRunLoopExit , // 退出 loop kCFRunLoopAllActivities // loop 所有狀態(tài)改變 }
我們需要監(jiān)測(cè)的狀態(tài)有兩個(gè):RunLoop 在進(jìn)入睡眠之前和喚醒后的兩個(gè) loop 狀態(tài)定義的值,分別是 kCFRunLoopBeforeSources 和 kCFRunLoopAfterWaiting ,也就是要觸發(fā) Source0 回調(diào)和接收 mach_port 消息兩個(gè)狀態(tài)。
三、如何檢查卡頓
說下步驟:
創(chuàng)建一個(gè) CFRunLoopObserverContext 觀察者;
將創(chuàng)建好的觀察者 runLoopObserver 添加到主線程 RunLoop 的 common 模式下觀察;
創(chuàng)建一個(gè)持續(xù)的子線程專門用來監(jiān)控主線程的 RunLoop 狀態(tài);
一旦發(fā)現(xiàn)進(jìn)入睡眠前的 kCFRunLoopBeforeSources 狀態(tài),或者喚醒后的狀態(tài) kCFRunLoopAfterWaiting,在設(shè)置的時(shí)間閾值內(nèi)一直沒有變化,即可判定為卡頓;
dump 出堆棧的信息,從而進(jìn)一步分析出具體是哪個(gè)方法的執(zhí)行時(shí)間過長(zhǎng);
上代碼:
#import <Foundation/Foundation.h> @interface SMLagMonitor : NSObject + (instancetype)shareInstance; - (void)beginMonitor; //開始監(jiān)視卡頓 - (void)endMonitor; //停止監(jiān)視卡頓 @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 { //監(jiān)測(cè) CPU 消耗 self.cpuMonitorTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(updateCPUInfo) userInfo:nil repeats:YES]; //監(jiān)測(cè)卡頓 if (runLoopObserver) { return; } dispatchSemaphore = dispatch_semaphore_create(0); //Dispatch Semaphore保證同步 //創(chuàng)建一個(gè)觀察者 CFRunLoopObserverContext context = {0,(__bridge void*)self,NULL,NULL}; runLoopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, &runLoopObserverCallBack, &context); //將觀察者添加到主線程runloop的common模式下的觀察中 CFRunLoopAddObserver(CFRunLoopGetMain(), runLoopObserver, kCFRunLoopCommonModes); //創(chuàng)建子線程監(jiān)控 dispatch_async(dispatch_get_global_queue(0, 0), ^{ //子線程開啟一個(gè)持續(xù)的loop用來進(jìn)行監(jiān)控 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; } //兩個(gè)runloop的狀態(tài),BeforeSources和AfterWaiting這兩個(gè)狀態(tài)區(qū)間時(shí)間能夠檢測(cè)到是否卡頓 if (runLoopActivity == kCFRunLoopBeforeSources || runLoopActivity == kCFRunLoopAfterWaiting) { // 將堆棧信息上報(bào)服務(wù)器的代碼放到這里 //出現(xiàn)三次出結(jié)果 // 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 時(shí)打印和記錄堆棧 NSString *reStr = smStackOfThread(threads[i]); //記錄數(shù)據(jù)庫中 // [[[SMLagDB shareInstance] increaseWithStackString:reStr] subscribeNext:^(id x) {}]; NSLog(@"CPU useage overload thread stack:\n%@",reStr); } } } } } @end
使用,直接在APP didFinishLaunchingWithOptions 方法里面這樣寫:
[[SMLagMonitor shareInstance] beginMonitor];
以上就是ios利用RunLoop原理實(shí)現(xiàn)去監(jiān)控卡頓實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于ios RunLoop去監(jiān)控卡頓的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
ios開發(fā)加載webview顯示進(jìn)度條實(shí)例
本篇文章主要介紹了ios開發(fā)加載webview顯示進(jìn)度條實(shí)例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05iOS Webview自適應(yīng)實(shí)際內(nèi)容高度的4種方法詳解
這篇文章主要介紹了iOS Webview自適應(yīng)實(shí)際內(nèi)容高度的4種方法詳解,本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09詳解iOS開發(fā)中UIPickerView控件的使用方法
這篇文章主要介紹了詳解iOS開發(fā)中UIPickerView控件的使用方法,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-11-11設(shè)計(jì)模式開發(fā)中的備忘錄模式在iOS應(yīng)用開發(fā)中的運(yùn)用實(shí)例
這篇文章主要介紹了設(shè)計(jì)模式開發(fā)中的備忘錄模式在iOS應(yīng)用開發(fā)中的實(shí)例,代碼為傳統(tǒng)的Objective-C,需要的朋友可以參考下2016-03-03IOS開發(fā) UIAlertController詳解及實(shí)例代碼
這篇文章主要介紹了 IOS開發(fā) UIAlertController詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2016-12-12iOS實(shí)現(xiàn)微信/QQ顯示最近拍攝圖片的功能實(shí)例代碼
如果你剛剛拍攝了圖片,在使用微信/QQ發(fā)生消息時(shí)會(huì)顯示“你可能要發(fā)送的圖片”,這個(gè)功能非常人性化,怎么實(shí)現(xiàn)的呢?下面小編給大家分享iOS實(shí)現(xiàn)微信/QQ顯示最近拍攝圖片的功能實(shí)例代碼,一起看看吧2017-03-03iOS swift 總結(jié)NavigationController出現(xiàn)問題及解決方法
這篇文章主要介紹了iOS swift 總結(jié)NavigationController出現(xiàn)問題及解決方法的相關(guān)資料,需要的朋友可以參考下2016-12-12iOS實(shí)現(xiàn)列表與網(wǎng)格兩種視圖的相互切換
相信大家應(yīng)該也都發(fā)現(xiàn)了,在現(xiàn)在很多的電商app中,都會(huì)有列表視圖和網(wǎng)格兩種視圖的相互切換。例如京東和淘寶。這樣更利于提高用戶的體驗(yàn)度,所以這篇文章小編就是大家分享下利用iOS實(shí)現(xiàn)列表與網(wǎng)格兩種視圖相互切換的方法,文中介紹的很詳細(xì),感興趣的下面來一起看看吧。2016-10-10