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
+40
View File
@@ -0,0 +1,40 @@
import Foundation
nonisolated enum EnergyReadStatus: String, Codable, Sendable {
case available, denied, gone, failed, identityChanged, deadline, unsupported, unverified
}
nonisolated enum EnergyCapability: String, Codable, Sendable { case verifiedCPU, unverified, unsupported, unavailable }
nonisolated struct ProcessEnergyRequest: Codable, Sendable {
let token: UUID
let identities: [ProcessIdentity]
static let limit = 256
static let byteLimit = 65_536
}
nonisolated struct ProcessEnergyReading: Codable, Sendable {
let id: ProcessIdentity
let birth: UInt64
let uptime: TimeInterval
let nanojoules: UInt64?
let status: EnergyReadStatus
}
nonisolated struct ProcessEnergyReply: Codable, Sendable {
let token: UUID
let capability: EnergyCapability
let readings: [ProcessEnergyReading]
}
nonisolated struct ProcessEnergyUsage: Identifiable, Sendable {
let process: ProcessMetrics
let watts: Double
let seconds: TimeInterval
var id: ProcessIdentity { process.id }
var formattedPower: String { watts >= 1 ? String(format: "%.2f W", watts) : String(format: "%.1f mW", watts * 1000) }
}
nonisolated struct ProcessEnergySnapshot: Sendable {
enum State: Sendable { case waiting, available, partial, unavailable, unsupported }
let date: Date
let candidates: Int
let readable: Int
let measured: Int
let rows: [ProcessEnergyUsage] // Only the top three; no CPU prefilter.
let state: State
}
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
nonisolated struct ProcessIdentity: Hashable, Sendable {
nonisolated struct ProcessIdentity: Hashable, Codable, Sendable {
let pid: Int32
let seconds: UInt64
let microseconds: UInt64
@@ -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))
}
}
+54 -16
View File
@@ -4,12 +4,18 @@ import Observation
@MainActor @Observable
final class MetricsStore {
private(set) var snapshot = MetricsSnapshot()
private(set) var processSnapshot: ProcessSnapshot?
private(set) var history = MetricHistory()
private(set) var energy: ProcessEnergySnapshot?
private(set) var isPaused = false
private(set) var isSystemSleeping = false
private(set) var isDisplaySleeping = false
private(set) var isPanelVisible = false
let sampling: SamplingPreferences
var effectiveMilliseconds: Int { isPanelVisible ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
private var hasSamplingDemand: Bool { isPanelVisible || sampling.backgroundEnabled }
private let energyEnabled: Bool
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
private var hasSamplingDemand: Bool { !isSystemSleeping && (panelDemand || sampling.backgroundEnabled) }
@ObservationIgnored private var generation = 0
@ObservationIgnored private var visibilityGeneration = 0
@ObservationIgnored private var task: Task<Void, Never>?
@@ -18,8 +24,9 @@ final class MetricsStore {
@ObservationIgnored private var needsHistoryBoundary = true
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler()) {
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler(), energyEnabled: Bool = true) {
self.sampler = sampler
self.energyEnabled = energyEnabled
self.sampling = sampling ?? SamplingPreferences()
self.sampling.onChange = { [weak self] in
guard let self, !self.isPaused,
@@ -31,6 +38,7 @@ final class MetricsStore {
func start() {
guard task == nil else { return }
if isPaused { energy = nil; visibilityGeneration += 1 }
isPaused = false
reschedule(reset: true)
}
@@ -57,21 +65,32 @@ final class MetricsStore {
while !Task.isCancelled {
let sampledAt = ContinuousClock.now
let visibleGeneration = self?.visibilityGeneration
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true,
includeSlowMetrics: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
var next = await sampler.sample(includeProcesses: self?.panelDemand == true,
includeSlowMetrics: self?.panelDemand == true,
maximumEnergyInterval: max(30, Double(self?.effectiveMilliseconds ?? 2000) / 500),
includeEnergy: self?.energyEnabled == true, demandRevision: visibleGeneration, processUpdate: { [weak self] processes in
Task { @MainActor [weak self] in
guard let self, self.visibilityGeneration == visibleGeneration,
self.isPanelVisible, !self.isPaused else { return }
if self.snapshot.processes.map({ $0.date > processes.date }) != true { self.snapshot.processes = processes }
self.panelDemand, !self.isPaused, !self.isSystemSleeping else { return }
if self.processSnapshot.map({ $0.date > processes.date }) != true { self.processSnapshot = processes }
}
}, energyUpdate: { [weak self] energy in
Task { @MainActor [weak self] in
guard let self, self.visibilityGeneration == visibleGeneration,
self.panelDemand, !self.isPaused, !self.isSystemSleeping else { return }
self.energy = energy
SamplingDiagnostics.recordEnergy(energy)
}
})
guard !Task.isCancelled, self?.generation == currentGeneration else { return }
if self?.isPanelVisible != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
else if let completed = self?.snapshot.processes, completed.date >= next.date {
if self?.panelDemand != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
else if let completed = self?.processSnapshot, completed.date >= next.date {
// A fast detached process result may reach MainActor before this quick snapshot.
next.processes = completed
}
self?.snapshot = next
var resources = next
resources.processes = nil
self?.snapshot = resources
self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true, expectedInterval: Double(self?.effectiveMilliseconds ?? 5_000) / 1000)
self?.lastPublishedAt = .now
self?.needsHistoryBoundary = false
@@ -92,20 +111,39 @@ final class MetricsStore {
visibilityGeneration += 1
task?.cancel()
task = nil
Task { await sampler.setProcessVisible(false) }
let revision = visibilityGeneration
Task { await sampler.setProcessVisible(false, revision: revision) }
isPaused = true
SamplingDiagnostics.record(snapshot, event: "pause")
}
}
func setSystemSleeping(_ sleeping: Bool) {
guard sleeping != isSystemSleeping else { return }
isSystemSleeping = sleeping
updateDemand(reset: true)
}
func setDisplaySleeping(_ sleeping: Bool) {
guard sleeping != isDisplaySleeping else { return }
isDisplaySleeping = sleeping
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
}
func setPanelVisible(_ visible: Bool) {
guard isPanelVisible != visible else { return }
visibilityGeneration += 1
isPanelVisible = visible
if !visible { snapshot.processes = nil }
let active = visible && !isPaused
Task { await sampler.setProcessVisible(active) }
if !isPaused { reschedule(reset: !sampling.backgroundEnabled) }
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
}
private func updateDemand(reset: Bool, sampleImmediately: Bool = true) {
visibilityGeneration += 1
let revision = visibilityGeneration
let active = panelDemand && !isPaused && !isSystemSleeping
if !active { processSnapshot = nil }
energy = nil
Task { await sampler.setProcessVisible(active, revision: revision) }
if !isPaused { reschedule(reset: reset, sampleImmediately: sampleImmediately) }
}
deinit { task?.cancel() }
@@ -0,0 +1,33 @@
import Foundation
nonisolated enum ProcessEnergyServiceClient {
static func read(_ identities: [ProcessIdentity]) async -> ([ProcessEnergyReading], EnergyCapability) {
var readings: [ProcessEnergyReading] = []
var capability: EnergyCapability = .unavailable
let deadline = ProcessInfo.processInfo.systemUptime + 3
for start in stride(from: 0, to: identities.count, by: ProcessEnergyRequest.limit) {
guard !Task.isCancelled, ProcessInfo.processInfo.systemUptime < deadline else { break }
let chunk = Array(identities[start..<min(start + ProcessEnergyRequest.limit, identities.count)])
let request = ProcessEnergyRequest(token: UUID(), identities: chunk)
guard let data = try? JSONEncoder().encode(request), data.count <= ProcessEnergyRequest.byteLimit else { continue }
let reply: ProcessEnergyReply? = await ServiceRequest.perform(timeout: min(1.5, deadline - ProcessInfo.processInfo.systemUptime)) { proxy, finish in
proxy.readProcessEnergy(data) { data in
guard let data, data.count <= 262_144,
let value = try? JSONDecoder().decode(ProcessEnergyReply.self, from: data), value.token == request.token,
value.readings.count == chunk.count,
Set(value.readings.map(\.id)) == Set(chunk) else { finish(nil); return }
finish(value)
}
}
if let reply {
if capability == .unavailable { capability = .unverified }
if reply.capability == .unsupported { return ([], .unsupported) }
if reply.capability == .verifiedCPU {
capability = .verifiedCPU
readings.append(contentsOf: reply.readings)
}
}
}
return (readings, capability)
}
}
@@ -2,6 +2,7 @@ import Foundation
/// Fixed read-only operation: no caller-supplied paths or commands.
@objc protocol SMARTServiceProtocol {
nonisolated func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> Void)
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
+18 -1
View File
@@ -5,7 +5,23 @@ import Darwin
nonisolated enum SamplingDiagnostics {
static let enabled = ProcessInfo.processInfo.environment["KYMO_DIAGNOSTICS"] == "1"
static func record(_ snapshot: MetricsSnapshot, event: String = "sample") {
static func recordTextPresentation(processes: Int, cells: Int) {
guard enabled else { return }
let line = "{\"event\":\"textPresentation\",\"processes\":\(processes),\"createdCells\":\(cells)}\n"
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
}
static func recordEnergy(_ snapshot: ProcessEnergySnapshot) {
guard enabled else { return }
let payload: [String: Any] = ["event": "energy", "recordedAt": Date().timeIntervalSince1970,
"state": String(describing: snapshot.state), "candidates": snapshot.candidates,
"readable": snapshot.readable, "measured": snapshot.measured,
"watts": snapshot.rows.map(\.watts), "intervals": snapshot.rows.map(\.seconds)]
guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) else { return }
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
}
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil) {
guard enabled else { return }
var payload: [String: Any] = [
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
@@ -14,6 +30,7 @@ nonisolated enum SamplingDiagnostics {
"pid": ProcessInfo.processInfo.processIdentifier,
"load": snapshot.load
]
payload["hiddenHostAlive"] = hiddenHostAlive
payload["cpu"] = snapshot.cpu?.usage
payload["cores"] = snapshot.cpu?.cores.count
payload["cpuTemperature"] = snapshot.cpuTemperature
+9 -3
View File
@@ -4,11 +4,17 @@ import Foundation
nonisolated struct SensorSchedule {
private(set) var deadline: TimeInterval = 0
private var failures = 0
private let successInterval: TimeInterval
private let failureInterval: TimeInterval
init(successInterval: TimeInterval = 10, failureInterval: TimeInterval = 60) {
self.successInterval = successInterval
self.failureInterval = failureInterval
}
func isDue(at now: TimeInterval) -> Bool { now >= deadline }
mutating func complete(available: Bool, at now: TimeInterval) {
failures = available ? 0 : min(failures + 1, 5)
deadline = now + (available ? 10 : min(600, 60 * pow(2, Double(failures - 1))))
mutating func complete(available: Bool, at now: TimeInterval, retryInterval: TimeInterval? = nil) {
failures = available ? 0 : min(failures + 1, 8)
deadline = now + (retryInterval ?? (available ? successInterval : min(600, failureInterval * pow(2, Double(failures - 1)))))
}
}