import Foundation import Darwin nonisolated struct CPUMonitor { private var previous: [[UInt32]]? mutating func sample() -> CPUMetrics? { var count: natural_t = 0 var info: processor_info_array_t? var infoCount: mach_msg_type_number_t = 0 guard host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &count, &info, &infoCount) == KERN_SUCCESS, let info else { previous = nil; return nil } defer { vm_deallocate(mach_task_self_, vm_address_t(UInt(bitPattern: info)), vm_size_t(infoCount) * vm_size_t(MemoryLayout.stride)) } let ticks = (0.. CPUMetrics? { guard !ticks.isEmpty, ticks.count == previous.count, ticks.allSatisfy({ $0.count == Int(CPU_STATE_MAX) }), previous.allSatisfy({ $0.count == Int(CPU_STATE_MAX) }) else { return nil } let delta = zip(ticks, previous).map { now, old in zip(now, old).map { $0 &- $1 } } let totals = delta.map { $0.reduce(0.0) { $0 + Double($1) } } let total = totals.reduce(0, +) guard total > 0 else { return nil } let user = delta.reduce(0.0) { $0 + Double($1[Int(CPU_STATE_USER)]) + Double($1[Int(CPU_STATE_NICE)]) } let system = delta.reduce(0.0) { $0 + Double($1[Int(CPU_STATE_SYSTEM)]) } let cores = zip(delta, totals).map { values, total in total > 0 ? 1 - Double(values[Int(CPU_STATE_IDLE)]) / total : 0 } return CPUMetrics(usage: (user + system) / total, user: user / total, system: system / total, cores: cores) } }