Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraBenchmarks/Runner.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 Foundation4243/// How long and how often each benchmark is measured.44public struct BenchmarkConfiguration: Codable, Sendable, Equatable {45 /// "quick", "full" or a custom label.46 public var name: String47 /// Target measuring time per benchmark, in seconds (calibration and set-up excluded).48 public var timeBudget: Double49 /// Minimum number of samples of a `.standard` benchmark.50 public var minimumSamples: Int51 /// Minimum number of samples of a `.slow` benchmark.52 public var slowMinimumSamples: Int53 /// Upper bound on the number of samples.54 public var maximumSamples: Int55 /// A sample repeats the operation until it lasts at least this long, so that the clock56 /// resolution and the timing overhead stay negligible for nanosecond-scale operations.57 public var minimumSampleDuration: Double5859 public init(60 name: String, timeBudget: Double, minimumSamples: Int, slowMinimumSamples: Int,61 maximumSamples: Int = 2000, minimumSampleDuration: Double = 0.000_262 ) {63 self.name = name64 self.timeBudget = timeBudget65 self.minimumSamples = max(1, minimumSamples)66 self.slowMinimumSamples = max(1, slowMinimumSamples)67 self.maximumSamples = max(1, maximumSamples)68 self.minimumSampleDuration = minimumSampleDuration69 }7071 /// About 0.15 s per benchmark; one sample for the slow ones.72 public static let quick = BenchmarkConfiguration(name: "quick", timeBudget: 0.15, minimumSamples: 3, slowMinimumSamples: 1)73 /// About 1 s per benchmark; at least three samples for the slow ones.74 public static let full = BenchmarkConfiguration(name: "full", timeBudget: 1.0, minimumSamples: 5, slowMinimumSamples: 3)75 /// Smallest useful run (tests): every benchmark executes, numbers are not meaningful.76 public static let smoke = BenchmarkConfiguration(77 name: "smoke", timeBudget: 0.002, minimumSamples: 1, slowMinimumSamples: 1, maximumSamples: 3, minimumSampleDuration: 0)78}7980/// Result of one benchmark.81public struct BenchmarkResult: Codable, Sendable, Equatable, Identifiable {82 public let id: String83 public let family: BenchmarkFamily84 public let algorithm: String85 public let operation: String86 public let metric: BenchmarkMetric87 public let unitsPerOperation: Double88 public let unitLabel: String?89 public let sizes: BenchmarkSizes?90 public let cost: BenchmarkCost91 /// Seconds per operation over the samples.92 public let statistics: BenchmarkStatistics93 /// Operations per sample (batching of very short operations).94 public let operationsPerSample: Int95 /// Total measured operations = samples x operationsPerSample.96 public let iterations: Int97 /// False when the calibration run was kept as the first sample (slow benchmark, no warm-up).98 public let warmedUp: Bool99 /// Wall-clock time of the measured samples, in seconds.100 public let wallTime: Double101 /// User + system CPU time of the process during the measured samples, in seconds.102 /// It is the proxy for energy: no per-process energy counter exists for applications.103 public let cpuTime: Double104 /// Resident size after the samples minus before, in bytes. Approximate (whole process, allocator105 /// caching, other threads); nil when `task_info` is unavailable.106 public let residentDelta: Int64?107 /// Increase of the process resident high-water mark during the benchmark, set-up included, in108 /// bytes. Approximate: 0 when an earlier benchmark already reached a higher peak.109 public let peakResidentIncrease: Int64?110 /// Thermal state when the benchmark ended.111 public let thermalStateAtEnd: String112113 public var displayName: String { "\(algorithm) \(operation)" }114115 /// Operations per second from the median.116 public var operationsPerSecond: Double { statistics.median > 0 ? 1 / statistics.median : 0 }117118 /// CPU time (user + system, all threads of the process) per operation, in seconds. Larger than the119 /// wall-clock mean when the engine spreads the operation over several cores (SLH-DSA).120 public var cpuTimePerOperation: Double { iterations > 0 ? cpuTime / Double(iterations) : 0 }121122 /// CPU time divided by wall-clock time over the samples: about 1 for single-threaded code,123 /// about the number of busy cores for multi-threaded code.124 public var cpuUtilization: Double { wallTime > 0 ? cpuTime / wallTime : 0 }125126 /// Megabytes (10^6 bytes) per second from the median; nil unless the metric is `.throughput`.127 public var megabytesPerSecond: Double? {128 guard metric == .throughput, statistics.median > 0 else { return nil }129 return unitsPerOperation / statistics.median / 1_000_000130 }131132 /// Items per second from the median; nil unless the metric is `.rate` or `.timePerItem`.133 public var itemsPerSecond: Double? {134 guard metric == .rate || metric == .timePerItem, statistics.median > 0 else { return nil }135 return unitsPerOperation / statistics.median136 }137138 /// Nanoseconds per item from the median; nil unless the metric is `.rate` or `.timePerItem`.139 public var nanosecondsPerItem: Double? {140 guard metric == .rate || metric == .timePerItem, unitsPerOperation > 0 else { return nil }141 return statistics.median / unitsPerOperation * 1_000_000_000142 }143144 /// The figure to show first, with its unit: "42.1 µs", "118 MB/s", "5.2 M permutations/s", "310 ns/transform".145 public var headline: String {146 switch metric {147 case .time:148 return BenchmarkFormat.duration(statistics.median)149 case .throughput:150 return BenchmarkFormat.number(megabytesPerSecond ?? 0) + " MB/s"151 case .rate:152 return BenchmarkFormat.count(itemsPerSecond ?? 0) + " \(unitLabel ?? "item")s/s"153 case .timePerItem:154 return BenchmarkFormat.duration((nanosecondsPerItem ?? 0) / 1_000_000_000) + "/\(unitLabel ?? "item")"155 }156 }157}158159/// A benchmark that threw during set-up or measurement.160public struct BenchmarkFailure: Codable, Sendable, Equatable, Identifiable {161 public let id: String162 public let displayName: String163 public let message: String164}165166/// Complete output of a run.167public struct BenchmarkReport: Codable, Sendable, Equatable {168 public static let currentSchemaVersion = 1169170 public var schemaVersion: Int171 public var configuration: BenchmarkConfiguration172 public var environment: BenchmarkEnvironment173 public var startedAt: Date174 public var finishedAt: Date175 public var powerAtStart: PowerState176 public var powerAtEnd: PowerState177 /// One-minute load average of the machine when the run started and ended (all processes);178 /// nil when the system does not report it.179 public var loadAverageAtStart: Double?180 public var loadAverageAtEnd: Double?181 /// Wall-clock duration of the whole run (set-up included), in seconds.182 public var wallTime: Double183 /// User + system CPU time of the process over the whole run, in seconds.184 public var cpuTime: Double185 public var results: [BenchmarkResult]186 public var failures: [BenchmarkFailure]187188 /// "nominal → fair" when the thermal state changed during the run, otherwise the single state.189 public var thermalTransition: String {190 powerAtStart.thermalState == powerAtEnd.thermalState191 ? powerAtStart.thermalState : "\(powerAtStart.thermalState) → \(powerAtEnd.thermalState)"192 }193194 public func results(in family: BenchmarkFamily) -> [BenchmarkResult] {195 results.filter { $0.family == family }196 }197}198199/// Progress events of a run, delivered in order.200public enum BenchmarkProgress: Sendable {201 /// `index` is zero-based; `total` is the number of benchmarks of the run.202 case started(benchmark: Benchmark, index: Int, total: Int)203 case finished(result: BenchmarkResult, index: Int, total: Int)204 case failed(failure: BenchmarkFailure, index: Int, total: Int)205}206207/// Events of `BenchmarkRunner.events`: progress, then the report.208public enum BenchmarkEvent: Sendable {209 case progress(BenchmarkProgress)210 case completed(BenchmarkReport)211}212213/// Runs benchmarks one after the other on the calling task.214///215/// The work is CPU-bound and synchronous between suspension points: call `run` from a detached or216/// background task, never from the main actor. Cancellation is cooperative and checked between217/// samples, so a seconds-long operation (SLH-DSA "s" signature) finishes before the run stops.218public struct BenchmarkRunner: Sendable {219 public let configuration: BenchmarkConfiguration220221 public init(configuration: BenchmarkConfiguration = .quick) {222 self.configuration = configuration223 }224225 /// Runs `benchmarks` in order and returns the report. Throws `CancellationError` when the task226 /// is cancelled; a benchmark that throws is recorded in `failures` and the run continues.227 public func run(228 _ benchmarks: [Benchmark] = BenchmarkCatalogue.all,229 progress: @escaping @Sendable (BenchmarkProgress) -> Void = { _ in }230 ) async throws -> BenchmarkReport {231 let startedAt = Date()232 let powerAtStart = PowerState.current()233 let loadAtStart = SystemProbe.loadAverage()234 let cpuStart = SystemProbe.processCPUTime()235 let clock = ContinuousClock()236 let wallStart = clock.now237 var results = [BenchmarkResult]()238 var failures = [BenchmarkFailure]()239 results.reserveCapacity(benchmarks.count)240241 for (index, benchmark) in benchmarks.enumerated() {242 try Task.checkCancellation()243 progress(.started(benchmark: benchmark, index: index, total: benchmarks.count))244 do {245 let result = try measure(benchmark)246 results.append(result)247 progress(.finished(result: result, index: index, total: benchmarks.count))248 } catch is CancellationError {249 throw CancellationError()250 } catch {251 let failure = BenchmarkFailure(id: benchmark.id, displayName: benchmark.displayName, message: String(describing: error))252 failures.append(failure)253 progress(.failed(failure: failure, index: index, total: benchmarks.count))254 }255 await Task.yield()256 }257258 return BenchmarkReport(259 schemaVersion: BenchmarkReport.currentSchemaVersion,260 configuration: configuration,261 environment: .current(),262 startedAt: startedAt,263 finishedAt: Date(),264 powerAtStart: powerAtStart,265 powerAtEnd: .current(),266 loadAverageAtStart: loadAtStart,267 loadAverageAtEnd: SystemProbe.loadAverage(),268 wallTime: Self.seconds(clock.now - wallStart),269 cpuTime: SystemProbe.processCPUTime() - cpuStart,270 results: results,271 failures: failures272 )273 }274275 /// The same run as an asynchronous sequence, convenient for SwiftUI (`for try await event in ...`).276 /// The run executes on a background task of the given priority; ending the iteration cancels it.277 public func events(278 _ benchmarks: [Benchmark] = BenchmarkCatalogue.all, priority: TaskPriority = .userInitiated279 ) -> AsyncThrowingStream<BenchmarkEvent, Error> {280 AsyncThrowingStream { continuation in281 let task = Task.detached(priority: priority) {282 do {283 let report = try await run(benchmarks) { continuation.yield(.progress($0)) }284 continuation.yield(.completed(report))285 continuation.finish()286 } catch {287 continuation.finish(throwing: error)288 }289 }290 continuation.onTermination = { _ in task.cancel() }291 }292 }293294 /// Measures one benchmark synchronously: set-up, calibration (which is also the warm-up),295 /// then the samples. Throws `CancellationError` if the current task is cancelled between samples.296 public func measure(_ benchmark: Benchmark) throws -> BenchmarkResult {297 let clock = ContinuousClock()298 let peakBefore = SystemProbe.residentMemory()?.peak299 let body = try benchmark.prepare()300301 // Calibration: one operation, which also warms caches, lazy tables and the allocator.302 var memoryBefore = SystemProbe.residentMemory()303 var cpuBefore = SystemProbe.processCPUTime()304 var wallBefore = clock.now305 var start = clock.now306 try body()307 var estimate = Self.seconds(clock.now - start)308 try Task.checkCancellation()309310 let slow = benchmark.cost == .slow311 let minimumSamples = slow ? configuration.slowMinimumSamples : configuration.minimumSamples312 var samples = [Double]()313 var warmedUp = true314315 // Refine the estimate of short operations: the first call is often far slower than the rest.316 if estimate < configuration.minimumSampleDuration, configuration.minimumSampleDuration > 0 {317 var count = 1318 var elapsed = estimate319 while elapsed < configuration.minimumSampleDuration / 4, count < 1 << 20 {320 count *= 2321 start = clock.now322 for _ in 0..<count { try body() }323 elapsed = Self.seconds(clock.now - start)324 }325 estimate = max(elapsed / Double(count), 1e-10)326 }327328 let batch: Int329 if configuration.minimumSampleDuration > 0, estimate < configuration.minimumSampleDuration {330 batch = max(1, Int((configuration.minimumSampleDuration / estimate).rounded(.up)))331 } else {332 batch = 1333 }334 let perSample = estimate * Double(batch)335 var target = Int((configuration.timeBudget / max(perSample, 1e-10)).rounded(.down))336 target = min(max(target, minimumSamples), configuration.maximumSamples)337338 if slow, estimate >= configuration.timeBudget {339 // Seconds-long operation: the calibration run is a legitimate sample, keep it.340 samples.append(estimate)341 warmedUp = false342 target = max(minimumSamples, 1)343 }344 samples.reserveCapacity(target)345346 // The wall-clock, CPU-time and memory windows cover exactly the kept samples: they start347 // before the calibration run when it is kept, after the warm-up otherwise.348 if warmedUp {349 memoryBefore = SystemProbe.residentMemory()350 cpuBefore = SystemProbe.processCPUTime()351 wallBefore = clock.now352 }353 let deadline = clock.now.advanced(by: .seconds(configuration.timeBudget * 3))354 while samples.count < target {355 try Task.checkCancellation()356 start = clock.now357 if batch == 1 {358 try body()359 } else {360 for _ in 0..<batch { try body() }361 }362 let end = clock.now363 samples.append(Self.seconds(end - start) / Double(batch))364 // The estimate can be optimistic: never exceed three budgets once the minimum is reached.365 if samples.count >= minimumSamples, end > deadline { break }366 }367 let wall = Self.seconds(clock.now - wallBefore)368 let cpu = SystemProbe.processCPUTime() - cpuBefore369 let memoryAfter = SystemProbe.residentMemory()370371 var residentDelta: Int64?372 var peakIncrease: Int64?373 if let before = memoryBefore, let after = memoryAfter {374 residentDelta = Int64(after.current) - Int64(before.current)375 }376 if let before = peakBefore, let after = memoryAfter {377 peakIncrease = Int64(after.peak) - Int64(before)378 }379380 return BenchmarkResult(381 id: benchmark.id,382 family: benchmark.family,383 algorithm: benchmark.algorithm,384 operation: benchmark.operation,385 metric: benchmark.metric,386 unitsPerOperation: benchmark.unitsPerOperation,387 unitLabel: benchmark.unitLabel,388 sizes: benchmark.sizes,389 cost: benchmark.cost,390 statistics: BenchmarkStatistics(samples: samples),391 operationsPerSample: batch,392 iterations: samples.count * batch,393 warmedUp: warmedUp,394 wallTime: wall,395 cpuTime: cpu,396 residentDelta: residentDelta,397 peakResidentIncrease: peakIncrease,398 thermalStateAtEnd: PowerState.current().thermalState399 )400 }401402 static func seconds(_ duration: Duration) -> Double {403 let c = duration.components404 return Double(c.seconds) + Double(c.attoseconds) * 1e-18405 }406}407