检测使用主线程的时间百分比 [英] Detect percentage of time main thread is used

查看:64
本文介绍了检测使用主线程的时间百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测主线程繁忙时间的百分比,因此我可以在用户使用应用程序时记录该指标.目前,在答案

I am trying to detect the percentage of time that the Main thread is busy so I can log this metric when a user is using the app. Currently, the closest thing I can find is the user_time from basic_info with the help from an answer here but how can i know what thread is being used and if its the main thread? Then from here how can i tell how much of that time as a percentage of the apps total run time for that session?

推荐答案

所以我设法使用以下方法解决了这个问题:

So i managed to figure this out using the following:

class MainThreadAnalyser {
    typealias SumTotal = (total: Double, elements: Double)

    private var threadPercentages = [Double]()

    private let timeIntervalSeconds: Double

    init(timeIntervalSeconds: Double) {
        self.timeIntervalSeconds = timeIntervalSeconds
        if #available(iOS 10.0, *) {
            self.startCPUMonitoring(timeIntervalSeconds: self.timeIntervalSeconds)
        }
    }

    func getAverageCpuUsage() -> Double? {
        let sumTotal = threadPercentages.reduce((total: 0, elements: 0)) { (sum, item) -> SumTotal in
            var result = sum
            if item > 0 {
                result.total += item
                result.elements += 1
            }

            return result
        }

        return sumTotal.elements > 0 ? sumTotal.total / sumTotal.elements : nil
    }

    @available(iOS 10.0, *)
    private func startCPUMonitoring(timeIntervalSeconds: Double) {
        Timer.scheduledTimer(withTimeInterval: timeIntervalSeconds, repeats: true) { [weak self] _ in
            guard let strongSelf = self else { return }
            if let cpuUsage = strongSelf.cpuUsage() {
                strongSelf.threadPercentages.append(cpuUsage)
            }
        }
    }

    private func cpuUsage() -> Double? {
        var kernReturn: kern_return_t
        var taskInfoCount: mach_msg_type_number_t

        taskInfoCount = mach_msg_type_number_t(TASK_INFO_MAX)
        var tinfo = [integer_t](repeating: 0, count: Int(taskInfoCount))

        kernReturn = task_info(mach_task_self_, task_flavor_t(TASK_BASIC_INFO), &tinfo, &taskInfoCount)
        if kernReturn != KERN_SUCCESS {
            return -1
        }

        var threadArray: thread_act_array_t? = UnsafeMutablePointer(mutating: [thread_act_t]())
        var threadCount: mach_msg_type_number_t = 0
        defer {
            if let threadArray = threadArray {
                vm_deallocate(mach_task_self_, vm_address_t(UnsafePointer(threadArray).pointee), vm_size_t(threadCount))
            }
        }

        kernReturn = task_threads(mach_task_self_, &threadArray, &threadCount)

        if kernReturn != KERN_SUCCESS {
            return -1
        }

        var totalCPU: Double?

        if let threadArray = threadArray {

            for index in 0 ..< Int(threadCount) {
                var threadInfoCount = mach_msg_type_number_t(THREAD_INFO_MAX)
                var thinfo = [integer_t](repeating: 0, count: Int(threadInfoCount))
                kernReturn = thread_info(threadArray[index], thread_flavor_t(THREAD_BASIC_INFO),
                                 &thinfo, &threadInfoCount)
                if kernReturn != KERN_SUCCESS {
                    return -1
                }

                if index == 0 {
                    let cpuUse = thinfo[4]
                    totalCPU = Double(cpuUse/10)

                }
            }
        }

        return totalCPU
    }
}

这篇关于检测使用主线程的时间百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆