perf(efficiency): 接入真实CPU能量并隔离展示与采样需求

This commit is contained in:
2026-11-04 01:11:24 +08:00
parent a96d188abe
commit 1c26fc18f3
37 changed files with 1249 additions and 179 deletions
@@ -0,0 +1,49 @@
import Foundation
/// Uses system CPU energy attribution; never derives energy from CPU time or percentage.
nonisolated struct ProcessEnergyMonitor: Sendable {
private var previous: [ProcessIdentity: ProcessEnergyReading] = [:]
static func watts(current: ProcessEnergyReading, previous: ProcessEnergyReading?, maximumInterval: TimeInterval = 30) -> (Double, Double)? {
guard current.status == .available, let currentEnergy = current.nanojoules,
let previous, previous.status == .available, let previousEnergy = previous.nanojoules,
current.id == previous.id, current.birth != 0, current.birth == previous.birth,
currentEnergy >= previousEnergy else { return nil }
let elapsed = current.uptime - previous.uptime
guard elapsed.isFinite, elapsed > 0, maximumInterval.isFinite, elapsed <= maximumInterval else { return nil }
// Integer subtraction preserves low bits of large cumulative counters.
let power = Double(currentEnergy - previousEnergy) / 1_000_000_000 / elapsed
return power.isFinite && power >= 0 ? (power, elapsed) : nil
}
mutating func update(processes: ProcessSnapshot, readings: [ProcessEnergyReading], capability: EnergyCapability, maximumInterval: TimeInterval = 30) -> ProcessEnergySnapshot {
let processesByID = Dictionary(processes.rows.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
var next: [ProcessIdentity: ProcessEnergyReading] = [:]
var usages: [ProcessEnergyUsage] = []
var measured = 0
if capability == .verifiedCPU && !processes.failed {
for reading in readings where next[reading.id] == nil {
guard let process = processesByID[reading.id], reading.status == .available,
reading.nanojoules != nil, reading.birth > 0, reading.uptime.isFinite else { continue }
next[reading.id] = reading
if let (power, seconds) = Self.watts(current: reading, previous: previous[reading.id], maximumInterval: maximumInterval) {
measured += 1
let usage = ProcessEnergyUsage(process: process, watts: power, seconds: seconds)
let index = usages.firstIndex {
$0.watts < power || ($0.watts == power && $0.id.pid > process.id.pid)
} ?? usages.endIndex
usages.insert(usage, at: index)
if usages.count > 3 { usages.removeLast() }
}
}
}
previous = next // Failed / missing readings invalidate the old baseline.
let state: ProcessEnergySnapshot.State
if capability == .unsupported { state = .unsupported }
else if capability == .unavailable || processes.failed || (capability == .verifiedCPU && next.isEmpty) { state = .unavailable }
else if measured == 0 { state = .waiting }
else { state = measured < processes.enumerated ? .partial : .available }
return ProcessEnergySnapshot(date: Date(), candidates: processes.enumerated, readable: next.count,
measured: measured, rows: usages, state: state)
}
}
+45 -6
View File
@@ -30,11 +30,17 @@ actor SystemSampler {
private var nextBattery: TimeInterval = 0
private let processRead: @Sendable (inout ProcessMonitor) -> ProcessSnapshot
private var processMonitor = ProcessMonitor()
private var energyMonitor = ProcessEnergyMonitor()
private var energyTask: Task<Void, Never>?
private var energySchedule = SensorSchedule(successInterval: 5, failureInterval: 30)
private var maximumEnergyInterval: TimeInterval = 30
private var energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)?
private var processTask: Task<Void, Never>?
private var processCache: ProcessSnapshot?
private var processUpdate: (@Sendable (ProcessSnapshot) -> Void)?
private var processVisible = false
private var processGeneration = 0
private var demandRevision = Int.min
init(processRead: @escaping @Sendable (inout ProcessMonitor) -> ProcessSnapshot = { $0.sample() }) {
self.processRead = processRead
@@ -42,21 +48,34 @@ actor SystemSampler {
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
func setProcessVisible(_ visible: Bool) {
guard visible != processVisible else { return }
func setProcessVisible(_ visible: Bool, revision: Int? = nil) {
var changedRevision = false
if let revision {
guard revision >= demandRevision else { return }
changedRevision = revision != demandRevision
demandRevision = revision
}
guard visible != processVisible || changedRevision else { return }
processVisible = visible
processGeneration += 1
processCache = nil
if !visible { processUpdate = nil }
if !visible { processUpdate = nil; energyUpdate = nil }
energyTask?.cancel()
energyMonitor = ProcessEnergyMonitor()
energySchedule = SensorSchedule(successInterval: 5, failureInterval: 30)
processMonitor = ProcessMonitor()
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
}
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true,
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot {
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, includeEnergy: Bool = true, demandRevision: Int? = nil,
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil,
energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) -> MetricsSnapshot {
guard !Task.isCancelled else { return MetricsSnapshot() }
if let includeProcesses { setProcessVisible(includeProcesses) }
if let demandRevision, demandRevision < self.demandRevision { return MetricsSnapshot() }
setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision)
self.maximumEnergyInterval = min(3600, max(30, maximumEnergyInterval))
self.processUpdate = processUpdate
self.energyUpdate = includeEnergy ? energyUpdate : nil
if !didProbe {
didProbe = true
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() }
@@ -157,5 +176,25 @@ actor SystemSampler {
}
processMonitor = monitor; processCache = value
processUpdate?(value)
startEnergyIfNeeded(value)
}
private func startEnergyIfNeeded(_ processes: ProcessSnapshot) {
guard processVisible, energyUpdate != nil, energyTask == nil,
energySchedule.isDue(at: ProcessInfo.processInfo.systemUptime) else { return }
let generation = processGeneration
energyTask = Task { [self] in
let (readings, capability) = await ProcessEnergyServiceClient.read(processes.rows.map(\.id))
finishEnergy(processes, readings: readings, capability: capability, generation: generation)
}
}
private func finishEnergy(_ processes: ProcessSnapshot, readings: [ProcessEnergyReading],
capability: EnergyCapability, generation: Int) {
energyTask = nil
guard processVisible, processGeneration == generation else { return }
energySchedule.complete(available: capability == .verifiedCPU, at: ProcessInfo.processInfo.systemUptime,
retryInterval: capability == .unsupported ? 600 : nil)
energyUpdate?(energyMonitor.update(processes: processes, readings: readings, capability: capability, maximumInterval: maximumEnergyInterval))
}
}