網(wǎng)站首頁 編程語言 正文
一、卡頓問題的幾種原因
復(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];
原文鏈接:https://www.jianshu.com/p/fa0c5a3746e8
相關(guān)推薦
- 2022-06-01 C語言?超詳細(xì)介紹與實(shí)現(xiàn)線性表中的帶頭雙向循環(huán)鏈表_C 語言
- 2022-06-25 React服務(wù)端渲染和同構(gòu)的實(shí)現(xiàn)_React
- 2024-04-01 使用Vite安裝TailwindCSS
- 2022-04-17 Failed to bind properties under spring.servlet.mul
- 2021-09-25 Flutter實(shí)現(xiàn)底部彈窗效果_Android
- 2022-11-23 Android?IdleHandler基本使用及應(yīng)用案例詳解_Android
- 2022-03-21 golang?調(diào)用c語言動(dòng)態(tài)庫方式實(shí)現(xiàn)_Golang
- 2022-07-18 使用d2l包和相關(guān)環(huán)境配置的一些血淚心得
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支