Last active
October 23, 2024 11:26
-
-
Save nh7a/70832fa2658b591dca22e4606388a07f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
private let TASK_BASIC_INFO_COUNT = mach_msg_type_number_t(MemoryLayout<task_basic_info_data_t>.size / MemoryLayout<UInt32>.size) | |
private let TASK_VM_INFO_COUNT = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<UInt32>.size) | |
enum Process { | |
static var cpuUsage: Double { | |
var arr: thread_act_array_t? | |
var threadCount: mach_msg_type_number_t = 0 | |
guard task_threads(mach_task_self_, &arr, &threadCount) == KERN_SUCCESS else { return -1 } | |
guard let threads = arr else { return -1 } | |
defer { | |
let size = MemoryLayout<thread_t>.size * Int(threadCount) | |
vm_deallocate(mach_task_self_, vm_address_t(bitPattern: threads), vm_size_t(size)) | |
} | |
var total = 0.0 | |
for i in 0..<Int(threadCount) { | |
var info = thread_basic_info() | |
var infoCount = TASK_BASIC_INFO_COUNT | |
let kerr = withUnsafeMutablePointer(to: &info) { | |
$0.withMemoryRebound(to: integer_t.self, capacity: 1) { | |
thread_info(threads[i], thread_flavor_t(THREAD_BASIC_INFO), $0, &infoCount) | |
} | |
} | |
guard kerr == KERN_SUCCESS else { return -1 } | |
if info.flags & TH_FLAGS_IDLE == 0 { | |
total += Double(info.cpu_usage) / Double(TH_USAGE_SCALE) * 100.0 | |
} | |
} | |
return total | |
} | |
static var memoryUsage: Int { | |
var info = task_vm_info_data_t() | |
var infoCount = TASK_VM_INFO_COUNT | |
let kerr = withUnsafeMutablePointer(to: &info) { | |
$0.withMemoryRebound(to: integer_t.self, capacity: 1) { | |
task_info(mach_task_self_, thread_flavor_t(TASK_VM_INFO), $0, &infoCount) | |
} | |
} | |
guard kerr == KERN_SUCCESS else { return -1 } | |
return Int(info.internal) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment