Files
Kymo/kymo/Core/Monitors/CPUMonitor.swift
T

47 lines
2.2 KiB
Swift

import Foundation
import Darwin
nonisolated struct CPUMonitor {
private var previous: [[UInt32]]?
mutating func sample() -> CPUMetrics? {
// mach_host_self() returns a send right owned by this call, including failure paths.
let host = mach_host_self()
defer { mach_port_deallocate(mach_task_self_, host) }
var count: natural_t = 0
var info: processor_info_array_t?
var infoCount: mach_msg_type_number_t = 0
guard host_processor_info(host, 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<integer_t>.stride))
}
let ticks = (0..<Int(count)).map { core in
(0..<Int(CPU_STATE_MAX)).map { UInt32(bitPattern: info[core * Int(CPU_STATE_MAX) + $0]) }
}
defer { previous = ticks }
guard let previous, previous.count == ticks.count else { return nil }
return Self.calculate(current: ticks, previous: previous)
}
static func calculate(current ticks: [[UInt32]], previous: [[UInt32]]) -> 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)
}
}