Skip to content

Instantly share code, notes, and snippets.

@jacobsapps
Created August 5, 2025 06:14
Show Gist options
  • Save jacobsapps/9ba5dda9b7f611f25b18a723091cb106 to your computer and use it in GitHub Desktop.
Save jacobsapps/9ba5dda9b7f611f25b18a723091cb106 to your computer and use it in GitHub Desktop.
/// Gets current CPU usage percentage for the current app's threads
/// Returns a value between 0.0 and 100.0 representing CPU utilization
/// Uses thread-specific CPU usage tracking for accurate app performance metrics
func getCPUUsage() -> Double {
var totalUsageOfCPU = 0.0
var threadsList = UnsafeMutablePointer(mutating: [thread_act_t]())
var threadsCount = mach_msg_type_number_t(0)
let threadsResult = withUnsafeMutablePointer(to: &threadsList) {
$0.withMemoryRebound(to: thread_act_array_t?.self, capacity: 1) {
task_threads(mach_task_self_, $0, &threadsCount)
}
}
if threadsResult == KERN_SUCCESS {
for index in 0 ..< threadsCount {
var threadInfo = thread_basic_info()
var threadInfoCount = mach_msg_type_number_t(THREAD_INFO_MAX)
let infoResult = withUnsafeMutablePointer(to: &threadInfo) {
$0.withMemoryRebound(to: integer_t.self, capacity: 1) {
thread_info(threadsList[Int(index)], thread_flavor_t(THREAD_BASIC_INFO), $0, &threadInfoCount)
}
}
guard infoResult == KERN_SUCCESS else {
break
}
let threadBasicInfo = threadInfo as thread_basic_info
if threadBasicInfo.flags & TH_FLAGS_IDLE == 0 {
totalUsageOfCPU = (totalUsageOfCPU + (Double(threadBasicInfo.cpu_usage) / Double(TH_USAGE_SCALE)))
}
}
}
vm_deallocate(mach_task_self_, vm_address_t(UInt(bitPattern: threadsList)), vm_size_t(Int(threadsCount) * MemoryLayout<thread_t>.stride))
let cpuPercentage = totalUsageOfCPU * 100.0
return cpuPercentage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment