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?
            Asked
            
        
        
            Active
            
        
            Viewed 283 times
        
    3
            
            
        
        Wazza
        
- 1,725
 - 2
 - 17
 - 49
 
- 
                    What is the purpose? Can't you manage this inside `AppDelegate`? – Kamran Jul 17 '19 at 11:26
 
2 Answers
3
            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
    }
}
        Wazza
        
- 1,725
 - 2
 - 17
 - 49
 
0
            
            
        The main thread is being used constantly while the app is in the foreground. 
So you can schedule a timer in applicationDidBecomeActive and invalidate in applicationWillResignActive and get the accumulated seconds whenever you want.
        arturdev
        
- 10,884
 - 2
 - 39
 - 67