網站首頁 編程語言 正文
一、卡頓問題的幾種原因
復雜 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
相關推薦
- 2022-09-25 Shiro和SpringSecurity
- 2022-07-13 docker基本概念及安裝
- 2022-04-30 Python語言中的if語句詳情_python
- 2024-01-31 深入理解Python中的 `yield` 和 `yield from`
- 2022-10-12 pandas實現手機號號碼中間4位匿名化的示例代碼_python
- 2022-11-16 詳解C++中的左值,純右值和將亡值_C 語言
- 2022-06-22 git用戶自定義變量查看修改及調用教程詳解_其它綜合
- 2022-06-10 Asp.Net?Core使用Ocelot結合Consul實現服務注冊和發現_實用技巧
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支