最近参考Matrix做了卡顿监控的流程,整体流程思想就不多说了。这里注释了核心方法代码,做下记录,也方便大家阅读代码。
- 子线程监听-核心主流程
while (YES) {
@autoreleasepool {
if (g_bMonitor) {
SDumpType dumpType = [self check];
if (m_bStop) {
break;
}
if (dumpType != SDumpType_Unlag) {
// 主线程卡顿
if (SDumpType_BackgroundMainThreadBlock == dumpType || SDumpType_MainThreadBlock == dumpType) {
// 线程数超出64个时会导致主线程卡顿,如果卡顿是由于线程多造成的,那么就没必 要通过获取主线程堆栈去找卡顿原因了(线程过多时 CPU 在切换线程上下文时,还会更新寄存器,更新寄存器时需要寻址,而寻址的过程还会有较大的 CPU 消耗) 否则,不是因为线程过多造成的卡顿,则更新最近最耗时的堆栈,并回到主线程写入文件记录
if (g_CurrentThreadCount > 64) {
dumpType = SDumpType_BlockThreadTooMuch;
[self dumpWithType:dumpType];
} else {
// 需要过滤
SFilterType filterType = [self needFilter];
if (filterType == SFilterType_None) {
if (g_MainThreadHandle) {
if (g_PointMainThreadArray != NULL) {
free(g_PointMainThreadArray);
g_PointMainThreadArray = NULL;
g_PointStackCount = 0;
}
g_PointMainThreadArray = [m_pointMainThreadHandler getPointStack:g_PointStackCount];
g_PointMainThreadRepeatCountArray = [m_pointMainThreadHandler getPointStackRepeatCount];
[self dumpWithType:dumpType];
if (g_PointMainThreadArray != NULL) {
free(g_PointMainThreadArray);
g_PointMainThreadArray = NULL;
g_PointStackCount = 0;
}
} else {
[self dumpWithType:dumpType];
}
} else {
}
}
} else {
[self dumpWithType:dumpType];
}
} else {
// 没有卡顿,重置状态
[self resetStatus];
}
}
// 随着时间间隔变长, 每次主线程堆栈存储的次数就变多
// 代表当前堆栈卡顿时间很长
for (int nCnt = 0; nCnt < m_nIntervalTime && !m_bStop; nCnt++) {
if (g_MainThreadHandle && g_bMonitor) {
// 1s / 50ms
int intervalCount = g_CheckPeriodTime / g_PerStackInterval;
if (intervalCount <= 0) {
// 休眠 1s
usleep(g_CheckPeriodTime);
} else {
for (int index = 0; index < intervalCount && !m_bStop; index++) {
// 休眠 50ms
// 每50ms去获取主线程堆栈
usleep(g_PerStackInterval);
size_t stackBytes = sizeof(uintptr_t) * g_StackMaxCount;
uintptr_t *stackArray = (uintptr_t *)malloc(stackBytes);
if (stackArray == NULL) {
continue;
}
__block size_t nSum = 0;
memset(stackArray, 0, stackBytes);
// 暂停主线程, 获取线程堆栈
[SMachHelper getCurrentMainThreadStack:^(NSUInteger pc) {
stackArray[nSum] = (uintptr_t)pc;
nSum++;
} withMaxEntries:g_StackMaxCount];
// 最多存储10组堆栈, 每组堆栈最多50行
[m_pointMainThreadHandler addThreadStack:stackArray andStackCount:nSum];
}
}
} else {
// 休眠 1s
usleep(g_CheckPeriodTime);
}
}
if (m_bStop) {
break;
}
}
}
- 检查是否是卡顿
- (SDumpType)check {
BOOL tmp_g_bRun = g_bRun;
// runloop运行的最后时间
struct timeval tmp_g_tvRun = g_tvRun;
// 当前时间
struct timeval tvCur;
gettimeofday(&tvCur, NULL);
// 计算时间间隔, 但是微秒
unsigned long long diff = [SANRMonitor diffTime:&tmp_g_tvRun endTime:&tvCur];
// TODO: 目前g_tvSuspend就是启动时间,永远比tmp_g_tvRun小
struct timeval tmp_g_tvSuspend = g_tvSuspend;
if (__timercmp(&tmp_g_tvSuspend, &tmp_g_tvRun, >)) {
return SDumpType_Unlag;
}
m_blockDiffTime = 0;
// 运行中 & 运行时间非空 & 运行时间<当前时间 & 时间间隔>200ms
if (tmp_g_bRun && tmp_g_tvRun.tv_sec && tmp_g_tvRun.tv_usec && __timercmp(&tmp_g_tvRun, &tvCur, <) && diff > g_RunLoopTimeOut) {
m_blockDiffTime = diff;
// TODO: 一直在前端, 这个不会走
if (g_bBackgroundLaunch) {
return SDumpType_Unlag;
}
if (m_currentState == UIApplicationStateBackground) {
if (g_enterBackground.tv_sec != 0 || g_enterBackground.tv_usec != 0) {
// 计算在后台了多少时间=当前时间-进入后台时间
unsigned long long enterBackgroundTime = [SANRMonitor diffTime:&g_enterBackground endTime:&tvCur];
// TODO: 进入后台的时间<当前时间 & 在后台了的时间>180s
if (__timercmp(&g_enterBackground, &tvCur, <) && (enterBackgroundTime > APP_SHOULD_SUSPEND)) {
return SDumpType_Unlag;
}
}
return SDumpType_BackgroundMainThreadBlock;
}
return SDumpType_MainThreadBlock;
}
return SDumpType_Unlag;
}
- 过滤堆栈信息,判断是否有重复堆栈信息等... 避免重复记录
- (SFilterType)needFilter {
BOOL bIsSame = NO;
static std::vector<NSUInteger> vecCallStack(300);
__block NSUInteger nSum = 0;
__block NSUInteger stackFeat = 0; // use the top stack address;
// TODO: g_MainThreadHandle一直是YES
if (g_MainThreadHandle) {
nSum = [m_pointMainThreadHandler getLastMainThreadStackCount];
uintptr_t *stack = [m_pointMainThreadHandler getLastMainThreadStack];
if (stack) {
for (size_t i = 0; i < nSum; i++) {
vecCallStack[i] = stack[i];
}
// 获取最后堆栈的栈顶 符号地址
stackFeat = kssymbolicate_symboladdress(stack[0]);
} else {
nSum = 0;
}
}
// 堆栈层级太少 直接返回
if (nSum <= 1) {
return SFilterType_Meaningless;
}
// 判断堆栈是否和之前一样
if (nSum == m_lastMainThreadStackCount) {
NSUInteger index = 0;
for (index = 0; index < nSum; index++) {
if (vecCallStack[index] != m_vecLastMainThreadCallStack[index]) {
break;
}
}
if (index == nSum) {
bIsSame = YES;
}
}
if (bIsSame) {
// 如果堆栈记录与之前一样 则使用退火算法,修改检测时间间隔,每次增加1s
NSUInteger lastTimeInterval = m_nIntervalTime;
m_nIntervalTime = m_nLastTimeInterval + m_nIntervalTime;
m_nLastTimeInterval = lastTimeInterval;
return SFilterType_Annealing;
} else {
m_nIntervalTime = 1;
m_nLastTimeInterval = 1;
// 如果不一样 更新记录的最后一次调用栈
//update last call stack
m_vecLastMainThreadCallStack.clear();
m_lastMainThreadStackCount = 0;
for (NSUInteger index = 0; index < nSum; index++) {
m_vecLastMainThreadCallStack.push_back(vecCallStack[index]);
m_lastMainThreadStackCount++;
}
// 过滤重复的堆栈信息
// 如果栈顶符号存储过超过3次,那么认为重复记录
if (g_filterSameStack) {
NSUInteger repeatCnt = [m_stackHandler addStackFeat:stackFeat];
if (repeatCnt > g_triggerdFilterSameCnt) {
return SFilterType_TrigerByTooMuch;
}
}
return SFilterType_None;
}
}
- 找到重复最多的堆栈
- (uintptr_t *)getPointStack:(size_t &)count {
pthread_mutex_lock(&m_threadLock);
size_t maxValue = 0;
BOOL trueStack = NO;
for (int i = 0; i < m_cycleArrayCount; i++) {
size_t currentValue = m_topStackAddressRepeatArray[i];
int stackCount = (int)m_mainThreadStackCount[i];
// 找到10层以上 同时 次数最多的
if (currentValue >= maxValue && stackCount > SHORTEST_LENGTH_OF_STACK) {
maxValue = currentValue;
trueStack = YES;
}
}
if (!trueStack) {
pthread_mutex_unlock(&m_threadLock);
return NULL;
}
// 找到对应堆栈索引
size_t currentIndex = (m_tailPoint + m_cycleArrayCount - 1) % m_cycleArrayCount;
for (int i = 0; i < m_cycleArrayCount; i++) {
int trueIndex = (m_tailPoint + m_cycleArrayCount - i - 1) % m_cycleArrayCount;
int stackCount = (int)m_mainThreadStackCount[trueIndex];
if (m_topStackAddressRepeatArray[trueIndex] == maxValue && stackCount > SHORTEST_LENGTH_OF_STACK) {
currentIndex = trueIndex;
break;
}
}
// current count of point stack
size_t stackCount = m_mainThreadStackCount[currentIndex];
size_t pointThreadSize = sizeof(uintptr_t) * stackCount;
uintptr_t *pointThreadStack = (uintptr_t *)malloc(pointThreadSize);
size_t repeatCountArrayBytes = stackCount * sizeof(int);
m_mainThreadStackRepeatCountArray = (int *)malloc(repeatCountArrayBytes);
if (m_mainThreadStackRepeatCountArray != NULL) {
memset(m_mainThreadStackRepeatCountArray, 0, repeatCountArrayBytes);
}
// calculate the repeat count
for (size_t i = 0; i < stackCount; i++) {
for (int innerIndex = 0; innerIndex < m_cycleArrayCount; innerIndex++) {
size_t innerStackCount = m_mainThreadStackCount[innerIndex];
for (size_t idx = 0; idx < innerStackCount; idx++) {
// point stack i_th address compare to others
if (m_mainThreadStackCycleArray[currentIndex][i] == m_mainThreadStackCycleArray[innerIndex][idx]) {
m_mainThreadStackRepeatCountArray[i] += 1;
}
}
}
}
if (pointThreadStack != NULL) {
memset(pointThreadStack, 0, pointThreadSize);
for (size_t idx = 0; idx < stackCount; idx++) {
pointThreadStack[idx] = m_mainThreadStackCycleArray[currentIndex][idx];
}
pthread_mutex_unlock(&m_threadLock);
count = stackCount;
return pointThreadStack;
}
pthread_mutex_unlock(&m_threadLock);
return NULL;
}