fix(monitors): 按Mach时基修正进程CPU占用率

This commit is contained in:
2026-11-04 11:26:48 +08:00
parent 065c53622a
commit 40a7a55edf
6 changed files with 55 additions and 5 deletions
+12 -3
View File
@@ -6,9 +6,18 @@ nonisolated struct ProcessMonitor: Sendable {
private var sampleSerial: UInt64 = 0
private var paths: [ProcessIdentity: (name: String, path: String?, expires: TimeInterval)] = [:]
static func cpu(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
guard let previous, current >= previous, elapsed.isFinite, elapsed > 0 else { return nil }
return Double(current - previous) / 1_000_000_000 / elapsed
// PROC_PIDTASKALLINFO's task absolute CPU times use Mach ticks, not nanoseconds.
static let nanosecondsPerTick: Double = {
var scale = mach_timebase_info_data_t()
guard mach_timebase_info(&scale) == KERN_SUCCESS, scale.numer > 0, scale.denom > 0 else { return .nan }
return Double(scale.numer) / Double(scale.denom)
}()
static func cpu(current: UInt64, previous: UInt64?, elapsed: TimeInterval,
nanosecondsPerTick: Double = ProcessMonitor.nanosecondsPerTick) -> Double? {
guard let previous, current >= previous, elapsed.isFinite, elapsed > 0,
nanosecondsPerTick.isFinite, nanosecondsPerTick > 0 else { return nil }
return Double(current - previous) * nanosecondsPerTick / 1_000_000_000 / elapsed
}
mutating func sample() -> ProcessSnapshot {