卡頓監(jiān)控

最近參考Matrix做了卡頓監(jiān)控的流程,整體流程思想就不多說了。這里注釋了核心方法代碼,做下記錄,也方便大家閱讀代碼。

  1. 子線程監(jiān)聽-核心主流程
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) {
                        // 線程數(shù)超出64個時會導(dǎo)致主線程卡頓,如果卡頓是由于線程多造成的,那么就沒必 要通過獲取主線程堆棧去找卡頓原因了(線程過多時 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 {
                    // 沒有卡頓,重置狀態(tài)
                    [self resetStatus];
                }
            }

            // 隨著時間間隔變長, 每次主線程堆棧存儲的次數(shù)就變多
            // 代表當(dāng)前堆棧卡頓時間很長
            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;
            }
        }
    }
  1. 檢查是否是卡頓
- (SDumpType)check {

    BOOL tmp_g_bRun = g_bRun;
    
    // runloop運行的最后時間
    struct timeval tmp_g_tvRun = g_tvRun;

    // 當(dāng)前時間
    struct timeval tvCur;
    gettimeofday(&tvCur, NULL);
    
    // 計算時間間隔, 但是微秒
    unsigned long long diff = [SANRMonitor diffTime:&tmp_g_tvRun endTime:&tvCur];

    // TODO: 目前g_tvSuspend就是啟動時間,永遠(yuǎn)比tmp_g_tvRun小
    struct timeval tmp_g_tvSuspend = g_tvSuspend;
    if (__timercmp(&tmp_g_tvSuspend, &tmp_g_tvRun, >)) {
        return SDumpType_Unlag;
    }

    m_blockDiffTime = 0;
    
    // 運行中 & 運行時間非空 & 運行時間<當(dāng)前時間 & 時間間隔>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) {
                // 計算在后臺了多少時間=當(dāng)前時間-進(jìn)入后臺時間
                unsigned long long enterBackgroundTime = [SANRMonitor diffTime:&g_enterBackground endTime:&tvCur];
                // TODO: 進(jìn)入后臺的時間<當(dāng)前時間 & 在后臺了的時間>180s
                if (__timercmp(&g_enterBackground, &tvCur, <) && (enterBackgroundTime > APP_SHOULD_SUSPEND)) {
                    return SDumpType_Unlag;
                }
            }

            return SDumpType_BackgroundMainThreadBlock;
        }
        return SDumpType_MainThreadBlock;
    }

    return SDumpType_Unlag;
}
  1. 過濾堆棧信息,判斷是否有重復(fù)堆棧信息等... 避免重復(fù)記錄
- (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;

        // 如果不一樣 更新記錄的最后一次調(diào)用棧
        //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++;
        }

        // 過濾重復(fù)的堆棧信息
        // 如果棧頂符號存儲過超過3次,那么認(rèn)為重復(fù)記錄
        if (g_filterSameStack) {
            NSUInteger repeatCnt = [m_stackHandler addStackFeat:stackFeat];
            if (repeatCnt > g_triggerdFilterSameCnt) {
                return SFilterType_TrigerByTooMuch;
            }
        }
        return SFilterType_None;
    }
}
  1. 找到重復(fù)最多的堆棧
- (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層以上 同時 次數(shù)最多的
        if (currentValue >= maxValue && stackCount > SHORTEST_LENGTH_OF_STACK) {
            maxValue = currentValue;
            trueStack = YES;
        }
    }

    if (!trueStack) {
        pthread_mutex_unlock(&m_threadLock);
        return NULL;
    }

    // 找到對應(yīng)堆棧索引
    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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容