perf(menubar): 隔离卡片动效并推进 1.1 低开销版本

This commit is contained in:
2026-11-07 12:33:18 +08:00
parent 668bdab0b8
commit 5787193754
19 changed files with 362 additions and 34 deletions
+6 -5
View File
@@ -18,6 +18,7 @@ nonisolated struct NetworkMonitor {
private var previous: [String: (UInt64, UInt64)] = [:]
private var timestamp: TimeInterval?
private var identities: [String: String] = [:]
private var counterBuffer: [UInt8] = []
static func rate(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
guard let previous, elapsed.isFinite, elapsed > 0, current >= previous else { return nil }
@@ -25,7 +26,7 @@ nonisolated struct NetworkMonitor {
}
mutating func sample() -> [NetworkInterfaceMetrics]? {
guard let counters = Self.counters() else { previous = [:]; timestamp = nil; return nil }
guard let counters = counters() else { previous = [:]; timestamp = nil; return nil }
let now = ProcessInfo.processInfo.systemUptime
let elapsed = timestamp.map { now - $0 } ?? 0
let metadata = Self.interfaces()
@@ -78,19 +79,19 @@ nonisolated struct NetworkMonitor {
}
/// NET_RT_IFLIST2 exposes 64-bit counters, avoiding getifaddrs' 4 GB wrap.
private static func counters() -> [String: (UInt64, UInt64)]? {
private mutating func counters() -> [String: (UInt64, UInt64)]? {
var mib: [Int32] = [CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0]
// The interface list can grow between size and data queries.
for _ in 0..<3 {
var count = 0
guard sysctl(&mib, u_int(mib.count), nil, &count, nil, 0) == 0 else { return nil }
guard count > 0 else { return [:] }
var bytes = [UInt8](repeating: 0, count: count)
let success = bytes.withUnsafeMutableBytes { raw in
if counterBuffer.count < count { counterBuffer = [UInt8](repeating: 0, count: count) }
let success = counterBuffer.withUnsafeMutableBytes { raw in
sysctl(&mib, u_int(mib.count), raw.baseAddress, &count, nil, 0)
}
if success != 0 { if errno == ENOMEM { continue }; return nil }
return bytes.withUnsafeBytes { raw -> [String: (UInt64, UInt64)]? in
return counterBuffer.withUnsafeBytes { raw -> [String: (UInt64, UInt64)]? in
var result: [String: (UInt64, UInt64)] = [:]
var offset = 0
while offset < count {