perf(efficiency): 接入真实CPU能量并隔离展示与采样需求
This commit is contained in:
@@ -19,6 +19,30 @@ import SwiftUI
|
||||
try? await Task.sleep(for: .milliseconds(150))
|
||||
precondition(controller.panel.isVisible && visible)
|
||||
precondition(controller.panel.firstResponder === controller.panel, "Opening must not focus the interval editor")
|
||||
controller.presentation.isPinned = true
|
||||
let cover = NSWindow(contentRect: controller.panel.frame.insetBy(dx: -8, dy: -8),
|
||||
styleMask: [.borderless], backing: .buffered, defer: false)
|
||||
cover.isReleasedWhenClosed = false
|
||||
cover.isOpaque = true
|
||||
cover.backgroundColor = .black
|
||||
cover.level = NSWindow.Level(rawValue: controller.panel.level.rawValue + 1)
|
||||
cover.orderFrontRegardless()
|
||||
let coveredDeadline = ContinuousClock.now.advanced(by: .seconds(2))
|
||||
while visible && ContinuousClock.now < coveredDeadline { try? await Task.sleep(for: .milliseconds(20)) }
|
||||
precondition(controller.panel.isVisible && controller.presentation.isOpen && !visible,
|
||||
"A fully covered pinned panel must lose demand without closing its content")
|
||||
cover.orderOut(nil); cover.close()
|
||||
let uncoveredDeadline = ContinuousClock.now.advanced(by: .seconds(2))
|
||||
while !visible && ContinuousClock.now < uncoveredDeadline { try? await Task.sleep(for: .milliseconds(20)) }
|
||||
precondition(visible, "Uncovering must restore demand")
|
||||
controller.presentation.isPinned = false
|
||||
controller.panel.orderOut(nil)
|
||||
let hiddenDeadline = ContinuousClock.now.advanced(by: .seconds(2))
|
||||
while visible && ContinuousClock.now < hiddenDeadline { try? await Task.sleep(for: .milliseconds(20)) }
|
||||
precondition(!visible && controller.presentation.isOpen, "OS visibility loss must stop demand without closing content/state")
|
||||
controller.panel.makeKeyAndOrderFront(nil)
|
||||
try? await Task.sleep(for: .milliseconds(150))
|
||||
precondition(visible, "OS visibility restoration must restore sampling demand")
|
||||
precondition(controller.panel.canBecomeKey && !controller.panel.canBecomeMain)
|
||||
precondition(controller.statusMenu().items.first?.title == "hide")
|
||||
controller.togglePanel()
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import Foundation
|
||||
|
||||
@main struct ProcessEnergyChecks {
|
||||
static let id = ProcessIdentity(pid: 42, seconds: 100, microseconds: 2)
|
||||
static func reading(_ energy: UInt64?, at time: Double, id: ProcessIdentity = id,
|
||||
birth: UInt64 = 1, status: EnergyReadStatus = .available) -> ProcessEnergyReading {
|
||||
ProcessEnergyReading(id: id, birth: birth, uptime: time, nanojoules: energy, status: status)
|
||||
}
|
||||
static func main() {
|
||||
let wire = ProcessEnergyReply(token: UUID(), capability: .verifiedCPU, readings: [reading(UInt64.max - 1, at: 10)])
|
||||
let decoded = try! JSONDecoder().decode(ProcessEnergyReply.self, from: JSONEncoder().encode(wire))
|
||||
precondition(decoded.readings[0].nanojoules == UInt64.max - 1 && decoded.token == wire.token)
|
||||
let old = reading(UInt64.max - 2_000_000_000, at: 10)
|
||||
let now = reading(UInt64.max - 1_000_000_000, at: 15)
|
||||
precondition(ProcessEnergyMonitor.watts(current: now, previous: nil) == nil)
|
||||
precondition(ProcessEnergyMonitor.watts(current: now, previous: old)?.0 == 0.2)
|
||||
precondition(ProcessEnergyMonitor.watts(current: old, previous: now) == nil)
|
||||
precondition(ProcessEnergyMonitor.watts(current: reading(5, at: 15), previous: reading(5, at: 10))?.0 == 0)
|
||||
for invalid in [reading(nil, at: 15, status: .denied), reading(10, at: 10), reading(10, at: .nan),
|
||||
reading(10, at: 50), reading(10, at: 15, birth: 2),
|
||||
reading(10, at: 15, id: ProcessIdentity(pid: 42, seconds: 101, microseconds: 2))] {
|
||||
precondition(ProcessEnergyMonitor.watts(current: invalid, previous: reading(5, at: 10)) == nil)
|
||||
}
|
||||
func row(_ id: ProcessIdentity, _ cpu: Double) -> ProcessMetrics {
|
||||
ProcessMetrics(id: id, name: "fixture", path: nil, cpu: cpu, residentBytes: nil, threads: nil, restricted: false)
|
||||
}
|
||||
let id2 = ProcessIdentity(pid: 43, seconds: 100, microseconds: 2)
|
||||
let processes = ProcessSnapshot(date: Date(), enumerated: 3, readable: 2, rows: [row(id, 5), row(id2, 0.01)], failed: false)
|
||||
var monitor = ProcessEnergyMonitor()
|
||||
let first = monitor.update(processes: processes, readings: [reading(0, at: 10), reading(0, at: 10, id: id2)], capability: .verifiedCPU)
|
||||
precondition(first.state == .waiting && first.rows.isEmpty)
|
||||
let measured = monitor.update(processes: processes, readings: [reading(1_000_000_000, at: 15), reading(5_000_000_000, at: 15, id: id2)], capability: .verifiedCPU)
|
||||
precondition(measured.state == .partial && measured.rows.first?.id == id2 && measured.measured == 2)
|
||||
precondition(measured.rows.first?.watts == 1)
|
||||
_ = monitor.update(processes: processes, readings: [], capability: .unavailable)
|
||||
let recovered = monitor.update(processes: processes, readings: [reading(6_000_000_000, at: 20, id: id2)], capability: .verifiedCPU)
|
||||
precondition(recovered.rows.isEmpty, "Failure must not bridge a missing interval")
|
||||
let unsupported = monitor.update(processes: processes, readings: [], capability: .unsupported)
|
||||
precondition(unsupported.state == .unsupported && unsupported.rows.isEmpty)
|
||||
let unverified = monitor.update(processes: processes, readings: [reading(0, at: 25)], capability: .unverified)
|
||||
precondition(unverified.rows.isEmpty && unverified.readable == 0)
|
||||
print("PASS: exact large-integer deltas, first/zero/reset/reuse/gap/error/time boundaries, energy-vs-CPU ranking, partial coverage and no CPU fallback")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
@main struct ProcessEnergyReaderChecks {
|
||||
static func main() throws {
|
||||
var bsd = proc_bsdinfo()
|
||||
precondition(proc_pidinfo(getpid(), PROC_PIDTBSDINFO, 0, &bsd, Int32(MemoryLayout.size(ofValue: bsd))) > 0)
|
||||
let id = ProcessIdentity(pid: getpid(), seconds: bsd.pbi_start_tvsec, microseconds: bsd.pbi_start_tvusec)
|
||||
func read(_ ids: [ProcessIdentity]) throws -> ProcessEnergyReply {
|
||||
let request = ProcessEnergyRequest(token: UUID(), identities: ids)
|
||||
let data = try JSONEncoder().encode(request)
|
||||
let reply = try JSONDecoder().decode(ProcessEnergyReply.self, from: ProcessEnergyReader.read(data)!)
|
||||
precondition(reply.token == request.token && reply.readings.count == ids.count)
|
||||
return reply
|
||||
}
|
||||
usleep(10_000)
|
||||
let first = try read([id]).readings[0]
|
||||
#if arch(arm64)
|
||||
let start = ProcessInfo.processInfo.systemUptime
|
||||
var work: UInt64 = 1
|
||||
while ProcessInfo.processInfo.systemUptime - start < 0.15 { work = work &* 6364136223846793005 &+ 1 }
|
||||
usleep(10_000) // Let scheduler accounting include the completed CPU slice.
|
||||
let second = try read([id])
|
||||
precondition(second.capability == .verifiedCPU && second.readings[0].nanojoules! > first.nanojoules!)
|
||||
precondition(second.readings[0].birth == first.birth && second.readings[0].uptime > first.uptime)
|
||||
print("PASS: live same-UID CPU energy counter advances under controlled CPU work", work)
|
||||
#else
|
||||
precondition(first.status == .unsupported)
|
||||
#endif
|
||||
let wrong = ProcessIdentity(pid: getpid(), seconds: id.seconds + 1, microseconds: id.microseconds)
|
||||
let mismatched = try read([wrong])
|
||||
#if arch(arm64)
|
||||
precondition(mismatched.readings[0].status == .identityChanged)
|
||||
let denied = try read([ProcessIdentity(pid: 1, seconds: 1, microseconds: 0)])
|
||||
precondition(denied.readings[0].status == .denied || denied.readings[0].status == .gone)
|
||||
#endif
|
||||
precondition(ProcessEnergyReader.read(Data(repeating: 0, count: ProcessEnergyRequest.byteLimit + 1)) == nil)
|
||||
let duplicates = try JSONEncoder().encode(ProcessEnergyRequest(token: UUID(), identities: [id, id]))
|
||||
precondition(ProcessEnergyReader.read(duplicates) == nil)
|
||||
precondition(ProcessEnergyReader.read(Data("not json".utf8)) == nil)
|
||||
let tooMany = try JSONEncoder().encode(ProcessEnergyRequest(token: UUID(), identities: (1...257).map {
|
||||
ProcessIdentity(pid: Int32($0), seconds: 1, microseconds: 0)
|
||||
}))
|
||||
precondition(ProcessEnergyReader.read(tooMany) == nil)
|
||||
print("PASS: nonce/identity, permission, duplicate and byte/decode boundaries")
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
@main struct SamplingIntervalChecks {
|
||||
@MainActor static func main() async throws {
|
||||
@@ -26,15 +27,15 @@ import Foundation
|
||||
preferences.backgroundMilliseconds = 1_800_000
|
||||
let store = MetricsStore(sampling: preferences)
|
||||
store.setPanelVisible(true)
|
||||
try await until { store.snapshot.processes != nil }
|
||||
try await until { store.processSnapshot != nil }
|
||||
precondition(store.effectiveMilliseconds == 500)
|
||||
store.setPanelVisible(false)
|
||||
precondition(store.snapshot.processes == nil && store.effectiveMilliseconds == 1_800_000)
|
||||
precondition(store.processSnapshot == nil && store.effectiveMilliseconds == 1_800_000)
|
||||
try await Task.sleep(for: .milliseconds(200))
|
||||
let hiddenDate = store.snapshot.date
|
||||
preferences.panelMilliseconds = 700
|
||||
try await Task.sleep(for: .milliseconds(650))
|
||||
precondition(store.snapshot.date == hiddenDate && store.snapshot.processes == nil)
|
||||
precondition(store.snapshot.date == hiddenDate && store.processSnapshot == nil)
|
||||
preferences.backgroundMilliseconds = 500
|
||||
try await until { store.snapshot.date > hiddenDate }
|
||||
precondition(store.history.samples.last?.breakBefore == false)
|
||||
@@ -50,7 +51,7 @@ import Foundation
|
||||
try await Task.sleep(for: .milliseconds(650))
|
||||
precondition(store.isPaused && store.snapshot.date == paused)
|
||||
store.togglePause()
|
||||
try await until { store.snapshot.date > paused && store.snapshot.processes != nil }
|
||||
try await until { store.snapshot.date > paused && store.processSnapshot != nil }
|
||||
precondition(store.effectiveMilliseconds == 1_800_000)
|
||||
precondition(store.history.samples.last?.breakBefore == true)
|
||||
store.togglePause()
|
||||
@@ -75,11 +76,14 @@ import Foundation
|
||||
let changingStore = MetricsStore(sampling: changing, sampler: SystemSampler(processRead: { slowRead.read(&$0) }))
|
||||
changingStore.setPanelVisible(true)
|
||||
try await until { !changingStore.history.samples.isEmpty }
|
||||
precondition(changingStore.snapshot.processes == nil)
|
||||
precondition(changingStore.processSnapshot == nil)
|
||||
let countBeforeChange = changingStore.history.samples.count
|
||||
let resourceChanges = PublicationCount()
|
||||
withObservationTracking { _ = changingStore.snapshot } onChange: { resourceChanges.increment() }
|
||||
changing.panelMilliseconds = 1_800_000
|
||||
try await until { changingStore.snapshot.processes != nil }
|
||||
try await until { changingStore.processSnapshot != nil }
|
||||
precondition(changingStore.history.samples.count == countBeforeChange, "Rate changes must preserve in-flight process delivery without an extra quick sample")
|
||||
precondition(resourceChanges.value == 0, "Process completion must not invalidate resource snapshot observers")
|
||||
changingStore.togglePause()
|
||||
let dormantPreferences = SamplingPreferences(defaults: defaults)
|
||||
dormantPreferences.backgroundEnabled = false
|
||||
@@ -89,11 +93,11 @@ import Foundation
|
||||
precondition(dormant.history.samples.isEmpty && dormant.snapshot.memory == nil,
|
||||
"Hidden without a consumer must not perform even an initial full sample")
|
||||
dormant.setPanelVisible(true)
|
||||
try await until { dormant.snapshot.processes != nil }
|
||||
try await until { dormant.processSnapshot != nil }
|
||||
dormant.setPanelVisible(false)
|
||||
let hiddenCount = dormant.history.samples.count
|
||||
try await Task.sleep(for: .milliseconds(650))
|
||||
precondition(dormant.history.samples.count == hiddenCount && dormant.snapshot.processes == nil)
|
||||
precondition(dormant.history.samples.count == hiddenCount && dormant.processSnapshot == nil)
|
||||
dormantPreferences.backgroundEnabled = true
|
||||
dormantPreferences.backgroundMilliseconds = 500
|
||||
try await until { dormant.history.samples.count > hiddenCount }
|
||||
@@ -104,6 +108,38 @@ import Foundation
|
||||
dormant.setPanelVisible(true)
|
||||
try await until { dormant.history.samples.count > disabledCount }
|
||||
precondition(dormant.history.samples.last?.breakBefore == true)
|
||||
dormant.setDisplaySleeping(true)
|
||||
let darkCount = dormant.history.samples.count
|
||||
try await Task.sleep(for: .milliseconds(650))
|
||||
precondition(dormant.history.samples.count == darkCount && dormant.processSnapshot == nil && dormant.energy == nil)
|
||||
dormantPreferences.backgroundEnabled = true
|
||||
dormantPreferences.backgroundMilliseconds = 500
|
||||
try await until { dormant.history.samples.count > darkCount }
|
||||
precondition(dormant.processSnapshot == nil && dormant.energy == nil,
|
||||
"Explicit background trends may run with the display off, but process/energy scans must stay stopped")
|
||||
dormantPreferences.backgroundEnabled = false
|
||||
dormant.setDisplaySleeping(false)
|
||||
try await until { dormant.processSnapshot != nil }
|
||||
dormant.setSystemSleeping(true)
|
||||
let sleepingCount = dormant.history.samples.count
|
||||
try await Task.sleep(for: .milliseconds(650))
|
||||
precondition(dormant.isSystemSleeping && dormant.history.samples.count == sleepingCount && dormant.energy == nil)
|
||||
dormant.setSystemSleeping(false)
|
||||
try await until { dormant.history.samples.count > sleepingCount }
|
||||
precondition(dormant.history.samples.last?.breakBefore == true && dormant.snapshot.cpu == nil)
|
||||
let staleProbe = DelayedProcessRead(delay: 0.01)
|
||||
let stale = SystemSampler(processRead: { staleProbe.read(&$0) })
|
||||
await stale.setProcessVisible(false, revision: 2)
|
||||
_ = await stale.sample(includeProcesses: true, includeSlowMetrics: false, demandRevision: 1)
|
||||
try await Task.sleep(for: .milliseconds(100))
|
||||
precondition(staleProbe.count == 0, "A stale demand must not start any process work")
|
||||
await stale.setProcessVisible(true, revision: 3)
|
||||
await stale.setProcessVisible(false, revision: 2)
|
||||
_ = await stale.sample(includeSlowMetrics: false, demandRevision: 3)
|
||||
let liveDeadline = ContinuousClock.now.advanced(by: .seconds(2))
|
||||
while staleProbe.count == 0 && ContinuousClock.now < liveDeadline { try await Task.sleep(for: .milliseconds(20)) }
|
||||
precondition(staleProbe.count == 1, "A stale stop must not undo the newer visible demand")
|
||||
await stale.setProcessVisible(false, revision: 4)
|
||||
dormant.togglePause()
|
||||
print("PASS: defaults, 100ms quantization/clamping, independent persistence, invalid defaults, active/background wake, pause precedence, slow-interval initial processes and history boundary")
|
||||
}
|
||||
@@ -135,3 +171,10 @@ private final class DelayedProcessRead: @unchecked Sendable {
|
||||
return monitor.sample()
|
||||
}
|
||||
}
|
||||
|
||||
private final class PublicationCount: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var count = 0
|
||||
var value: Int { lock.lock(); defer { lock.unlock() }; return count }
|
||||
func increment() { lock.lock(); count += 1; lock.unlock() }
|
||||
}
|
||||
|
||||
@@ -25,6 +25,15 @@ import Foundation
|
||||
precondition(gpu.deadline == now + 10)
|
||||
gpu.complete(available: false, at: now + 10)
|
||||
precondition(gpu.deadline == now + 70)
|
||||
var energy = SensorSchedule(successInterval: 5, failureInterval: 30)
|
||||
energy.complete(available: true, at: 0)
|
||||
precondition(energy.deadline == 5)
|
||||
energy.complete(available: false, at: 5)
|
||||
precondition(energy.deadline == 35)
|
||||
energy.complete(available: false, at: 35)
|
||||
precondition(energy.deadline == 95)
|
||||
energy.complete(available: false, at: 95, retryInterval: 600)
|
||||
precondition(energy.deadline == 695)
|
||||
print("PASS: independent sensor cadences, exponential failure backoff, cap and recovery")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,14 +55,14 @@ import Foundation
|
||||
let store = MetricsStore()
|
||||
store.setPanelVisible(true)
|
||||
for _ in 0..<40 {
|
||||
if store.snapshot.processes != nil { break }
|
||||
if store.processSnapshot != nil { break }
|
||||
try? await Task.sleep(for: .milliseconds(200))
|
||||
}
|
||||
precondition(store.snapshot.processes?.readable ?? 0 > 0)
|
||||
precondition(store.processSnapshot?.readable ?? 0 > 0)
|
||||
store.setPanelVisible(false)
|
||||
precondition(store.snapshot.processes == nil)
|
||||
precondition(store.processSnapshot == nil)
|
||||
try? await Task.sleep(for: .milliseconds(2200))
|
||||
precondition(store.snapshot.processes == nil)
|
||||
precondition(store.processSnapshot == nil)
|
||||
store.togglePause()
|
||||
print("PASS: process CPU boundaries/live baseline, GPU range, VPN total exclusion, bounded interface history, visibility reset")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user