feat(monitors): 实现 CPU 内存采样诊断与菜单栏实时指标
接入 Mach CPU 差分、内存与负载采样、暂停恢复及按需诊断,合并菜单栏单一原生标题的显示修复。 保留核心检查和本机交互验收记录;长期资源预算仍待验收。
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
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<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)
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user