51 lines
2.2 KiB
Swift
51 lines
2.2 KiB
Swift
import Foundation
|
|
import IOKit
|
|
|
|
nonisolated struct DiskIOMetrics: Sendable {
|
|
let read: Double?
|
|
let written: Double?
|
|
}
|
|
|
|
/// Driver counters describe physical block IO, not per-volume file traffic.
|
|
nonisolated struct DiskIOMonitor {
|
|
private var previous: [UInt64: (UInt64, UInt64)] = [:]
|
|
private var timestamp: TimeInterval?
|
|
|
|
mutating func sample() -> DiskIOMetrics? {
|
|
var iterator: io_iterator_t = 0
|
|
guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOBlockStorageDriver"), &iterator) == KERN_SUCCESS else {
|
|
previous = [:]; timestamp = nil; return nil
|
|
}
|
|
defer { IOObjectRelease(iterator) }
|
|
var counters: [UInt64: (UInt64, UInt64)] = [:]
|
|
while true {
|
|
let service = IOIteratorNext(iterator)
|
|
guard service != 0 else { break }
|
|
defer { IOObjectRelease(service) }
|
|
var identifier: UInt64 = 0
|
|
guard IORegistryEntryGetRegistryEntryID(service, &identifier) == KERN_SUCCESS,
|
|
let stats = IORegistryEntryCreateCFProperty(service, "Statistics" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? [String: Any],
|
|
let read = stats["Bytes (Read)"] as? UInt64,
|
|
let written = stats["Bytes (Write)"] as? UInt64 else { continue }
|
|
counters[identifier] = (read, written)
|
|
}
|
|
let now = ProcessInfo.processInfo.systemUptime
|
|
defer { previous = counters; timestamp = now }
|
|
guard !counters.isEmpty else { return nil }
|
|
guard let timestamp, Set(counters.keys) == Set(previous.keys) else {
|
|
return DiskIOMetrics(read: nil, written: nil)
|
|
}
|
|
var read: Double = 0
|
|
var written: Double = 0
|
|
for (id, current) in counters {
|
|
guard let old = previous[id],
|
|
let r = NetworkMonitor.rate(current: current.0, previous: old.0, elapsed: now - timestamp),
|
|
let w = NetworkMonitor.rate(current: current.1, previous: old.1, elapsed: now - timestamp) else {
|
|
return DiskIOMetrics(read: nil, written: nil)
|
|
}
|
|
read += r; written += w
|
|
}
|
|
return DiskIOMetrics(read: read, written: written)
|
|
}
|
|
}
|