Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraBenchmarks/SystemProbe.swift8// Module : Qyvora Benchmarks9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraCrypto4344#if canImport(Darwin)45@preconcurrency import Darwin46#endif4748/// Description of the machine and of the build that produced a report.49public struct BenchmarkEnvironment: Codable, Sendable, Equatable {50 /// `hw.machine` on iOS (e.g. iPhone18,2), `hw.model` on macOS (e.g. Mac17,6).51 public var deviceModel: String52 /// `hw.model` as reported (board identifier on iOS).53 public var hardwareModel: String54 /// `machdep.cpu.brand_string`, empty when the system does not expose it.55 public var cpuBrand: String56 public var physicalCores: Int57 public var logicalCores: Int58 /// `hw.perflevel0.physicalcpu` (performance cores), nil when not exposed.59 public var performanceCores: Int?60 /// `hw.perflevel1.physicalcpu` (efficiency cores), nil when not exposed.61 public var efficiencyCores: Int?62 public var memoryBytes: UInt6463 /// macOS, iOS, ...64 public var osName: String65 public var osVersion: String66 /// "debug" or "release": how the benchmark library itself was compiled.67 public var buildConfiguration: String68 /// `QyvoraEngine.version`.69 public var engineVersion: String7071 public static func current() -> BenchmarkEnvironment {72 let hwModel = SystemProbe.sysctlString("hw.model")73 let machine = SystemProbe.sysctlString("hw.machine")74 #if os(macOS)75 let device = hwModel.isEmpty ? machine : hwModel76 let os = "macOS"77 #elseif os(iOS)78 let device = machine.isEmpty ? hwModel : machine79 let os = "iOS"80 #elseif os(tvOS)81 let device = machine82 let os = "tvOS"83 #elseif os(watchOS)84 let device = machine85 let os = "watchOS"86 #elseif os(visionOS)87 let device = machine88 let os = "visionOS"89 #else90 let device = machine91 let os = "unknown"92 #endif93 let v = ProcessInfo.processInfo.operatingSystemVersion94 return BenchmarkEnvironment(95 deviceModel: device,96 hardwareModel: hwModel,97 cpuBrand: SystemProbe.sysctlString("machdep.cpu.brand_string"),98 physicalCores: SystemProbe.sysctlInt("hw.physicalcpu") ?? ProcessInfo.processInfo.processorCount,99 logicalCores: SystemProbe.sysctlInt("hw.logicalcpu") ?? ProcessInfo.processInfo.activeProcessorCount,100 performanceCores: SystemProbe.sysctlInt("hw.perflevel0.physicalcpu"),101 efficiencyCores: SystemProbe.sysctlInt("hw.perflevel1.physicalcpu"),102 memoryBytes: ProcessInfo.processInfo.physicalMemory,103 osName: os,104 osVersion: "\(v.majorVersion).\(v.minorVersion).\(v.patchVersion)",105 buildConfiguration: SystemProbe.buildConfiguration,106 engineVersion: QyvoraEngine.version107 )108 }109110 /// One line for report headers.111 public var summary: String {112 let cpu = cpuBrand.isEmpty ? "" : ", \(cpuBrand)"113 var cores = "\(physicalCores) cores"114 if let p = performanceCores, let e = efficiencyCores { cores += " (\(p) performance + \(e) efficiency)" }115 let gib = Double(memoryBytes) / 1_073_741_824116 return "\(deviceModel)\(cpu), \(cores), \(String(format: "%.0f", gib)) GiB, \(osName) \(osVersion), \(buildConfiguration) build"117 }118}119120/// Thermal state and low-power mode as reported by `ProcessInfo`.121public struct PowerState: Codable, Sendable, Equatable {122 /// nominal, fair, serious or critical.123 public var thermalState: String124 public var lowPowerMode: Bool125126 public init(thermalState: String, lowPowerMode: Bool) {127 self.thermalState = thermalState128 self.lowPowerMode = lowPowerMode129 }130131 public static func current() -> PowerState {132 let info = ProcessInfo.processInfo133 let thermal: String134 switch info.thermalState {135 case .nominal: thermal = "nominal"136 case .fair: thermal = "fair"137 case .serious: thermal = "serious"138 case .critical: thermal = "critical"139 @unknown default: thermal = "unknown"140 }141 return PowerState(thermalState: thermal, lowPowerMode: info.isLowPowerModeEnabled)142 }143}144145/// Process-level probes. None of them is an energy counter: iOS and macOS give applications no146/// per-process energy reading, so reports carry CPU time and thermal state as proxies.147public enum SystemProbe {148 public static var buildConfiguration: String {149 #if DEBUG150 return "debug"151 #else152 return "release"153 #endif154 }155156 public static func sysctlString(_ name: String) -> String {157 #if canImport(Darwin)158 var size = 0159 guard sysctlbyname(name, nil, &size, nil, 0) == 0, size > 0 else { return "" }160 var buffer = [UInt8](repeating: 0, count: size)161 guard sysctlbyname(name, &buffer, &size, nil, 0) == 0 else { return "" }162 let end = buffer.firstIndex(of: 0) ?? buffer.count163 return String(decoding: buffer[..<end], as: UTF8.self)164 #else165 return ""166 #endif167 }168169 public static func sysctlInt(_ name: String) -> Int? {170 #if canImport(Darwin)171 var value: Int64 = 0172 var size = MemoryLayout<Int64>.size173 guard sysctlbyname(name, &value, &size, nil, 0) == 0 else { return nil }174 if size == MemoryLayout<Int32>.size { return Int(Int32(truncatingIfNeeded: value)) }175 return Int(value)176 #else177 return nil178 #endif179 }180181 /// The two figures of `task_info(MACH_TASK_BASIC_INFO)` exactly as the kernel returns them, in bytes: the resident182 /// size and the kernel's high-water mark of it. Nil when the call fails.183 ///184 /// They are two counters, not one consistent pair: `resident_size` is computed when the call is made, while185 /// `resident_size_max` is a mark the kernel keeps up to date on its own schedule. While other threads of the186 /// process fault pages in, the size read can be a little above the mark read in the same call (observed on187 /// macOS 27 / Apple silicon: see `ProbeTests`). Use `residentMemory()` unless the raw pair is what is studied.188 public static func rawResidentMemory() -> (current: UInt64, kernelPeak: UInt64)? {189 #if canImport(Darwin)190 var info = mach_task_basic_info()191 var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size / MemoryLayout<natural_t>.size)192 let result = withUnsafeMutablePointer(to: &info) { pointer in193 pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {194 task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)195 }196 }197 guard result == KERN_SUCCESS else { return nil }198 return (UInt64(info.resident_size), UInt64(info.resident_size_max))199 #else200 return nil201 #endif202 }203204 private static let peakLock = NSLock()205 nonisolated(unsafe) private static var observedPeak: UInt64 = 0206207 /// Resident size and its high-water mark, in bytes. Nil when the kernel call fails.208 ///209 /// `peak` is a high-water mark in the plain sense: the largest of the kernel's mark and of every resident size210 /// this probe has read in the process, so `peak >= current` holds for every answer and `peak` never decreases211 /// from one call to the next. (The kernel's two figures alone do not guarantee either: `rawResidentMemory`.)212 /// A size the process reached between two calls of the probe and that the kernel's mark missed is not seen.213 public static func residentMemory() -> (current: UInt64, peak: UInt64)? {214 guard let raw = rawResidentMemory() else { return nil }215 peakLock.lock()216 defer { peakLock.unlock() }217 observedPeak = max(observedPeak, raw.kernelPeak, raw.current)218 return (raw.current, observedPeak)219 }220221 /// One-minute load average of the machine (`getloadavg`), nil when unavailable. A value well222 /// above 1 at the start of a run means that other processes compete for the cores.223 public static func loadAverage() -> Double? {224 #if canImport(Darwin)225 var load = [Double](repeating: 0, count: 3)226 guard getloadavg(&load, 3) >= 1 else { return nil }227 return load[0]228 #else229 return nil230 #endif231 }232233 /// User + system CPU time consumed by the process so far (`getrusage(RUSAGE_SELF)`), in seconds.234 public static func processCPUTime() -> Double {235 #if canImport(Darwin)236 var usage = rusage()237 guard getrusage(RUSAGE_SELF, &usage) == 0 else { return 0 }238 let user = Double(usage.ru_utime.tv_sec) + Double(usage.ru_utime.tv_usec) / 1_000_000239 let system = Double(usage.ru_stime.tv_sec) + Double(usage.ru_stime.tv_usec) / 1_000_000240 return user + system241 #else242 return 0243 #endif244 }245}246