Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraBenchmarks/Renderers.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/// Number formatting shared by the renderers and usable by the application.44public enum BenchmarkFormat {45 /// Three significant digits, without exponent.46 public static func number(_ value: Double) -> String {47 guard value.isFinite else { return "–" }48 let magnitude = abs(value)49 if magnitude == 0 { return "0" }50 if magnitude >= 100 { return String(format: "%.0f", value) }51 if magnitude >= 10 { return String(format: "%.1f", value) }52 if magnitude >= 1 { return String(format: "%.2f", value) }53 return String(format: "%.3f", value)54 }5556 /// Duration given in seconds, with the unit that keeps 1 ... 999 in front: ns, µs, ms, s.57 public static func duration(_ seconds: Double) -> String {58 guard seconds.isFinite else { return "–" }59 let magnitude = abs(seconds)60 if magnitude >= 1 { return number(seconds) + " s" }61 if magnitude >= 1e-3 { return number(seconds * 1e3) + " ms" }62 if magnitude >= 1e-6 { return number(seconds * 1e6) + " µs" }63 return number(seconds * 1e9) + " ns"64 }6566 /// Large counts: 12.3 k, 4.56 M.67 public static func count(_ value: Double) -> String {68 let magnitude = abs(value)69 if magnitude >= 1e9 { return number(value / 1e9) + " G" }70 if magnitude >= 1e6 { return number(value / 1e6) + " M" }71 if magnitude >= 1e3 { return number(value / 1e3) + " k" }72 return number(value)73 }7475 /// Signed memory quantity in binary units.76 public static func memory(_ bytes: Int64?) -> String {77 guard let bytes else { return "n/a" }78 let magnitude = Double(abs(bytes))79 let sign = bytes < 0 ? "−" : (bytes > 0 ? "+" : "")80 if magnitude >= 1_048_576 { return sign + number(magnitude / 1_048_576) + " MiB" }81 if magnitude >= 1024 { return sign + number(magnitude / 1024) + " KiB" }82 return sign + String(format: "%.0f", magnitude) + " B"83 }84}8586public extension BenchmarkReport {87 /// Pretty-printed JSON with sorted keys and ISO 8601 dates.88 func jsonData() throws -> Data {89 let encoder = JSONEncoder()90 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]91 encoder.dateEncodingStrategy = .iso860192 return try encoder.encode(self)93 }9495 func jsonString() throws -> String {96 String(decoding: try jsonData(), as: UTF8.self)97 }9899 /// Decodes a report written by `jsonData()`.100 init(jsonData: Data) throws {101 let decoder = JSONDecoder()102 decoder.dateDecodingStrategy = .iso8601103 self = try decoder.decode(BenchmarkReport.self, from: jsonData)104 }105106 /// Markdown document: environment, one table per family, failures.107 func markdown() -> String { MarkdownRenderer.render(self) }108}109110/// Markdown rendering of reports and of the size table.111public enum MarkdownRenderer {112 public static func render(_ report: BenchmarkReport) -> String {113 var out = "# QYVORA benchmark report\n\n"114 out += environmentSection(report)115 for family in BenchmarkFamily.allCases {116 let results = report.results(in: family)117 if results.isEmpty { continue }118 out += "\n## \(family.title)\n\n"119 out += table(results)120 }121 if !report.failures.isEmpty {122 out += "\n## Failures\n\n"123 for failure in report.failures { out += "- `\(failure.id)`: \(failure.message)\n" }124 }125 return out126 }127128 public static func environmentSection(_ report: BenchmarkReport) -> String {129 let e = report.environment130 let formatter = ISO8601DateFormatter()131 var out = ""132 out += "- Machine: \(e.deviceModel)\(e.cpuBrand.isEmpty ? "" : " (\(e.cpuBrand))")\n"133 var cores = "\(e.physicalCores) physical, \(e.logicalCores) logical"134 if let p = e.performanceCores, let eff = e.efficiencyCores { cores += " (\(p) performance + \(eff) efficiency)" }135 out += "- Cores: \(cores)\n"136 out += "- Memory: \(BenchmarkFormat.number(Double(e.memoryBytes) / 1_073_741_824)) GiB\n"137 out += "- System: \(e.osName) \(e.osVersion)\n"138 out += "- Build: \(e.buildConfiguration), engine \(e.engineVersion)\n"139 out += "- Mode: \(report.configuration.name) (\(BenchmarkFormat.number(report.configuration.timeBudget)) s per benchmark)\n"140 out += "- Started: \(formatter.string(from: report.startedAt)); wall time \(BenchmarkFormat.duration(report.wallTime)), "141 out += "CPU time \(BenchmarkFormat.duration(report.cpuTime)) (user + system)\n"142 out += "- Thermal state: \(report.thermalTransition); low-power mode: "143 out += "\(report.powerAtStart.lowPowerMode ? "on" : "off") at start, \(report.powerAtEnd.lowPowerMode ? "on" : "off") at end\n"144 if let start = report.loadAverageAtStart, let end = report.loadAverageAtEnd {145 out += "- Machine load average (1 min, all processes): \(BenchmarkFormat.number(start)) at start, \(BenchmarkFormat.number(end)) at end\n"146 }147 out += "- Energy: not measured (no per-process energy counter is available to applications); CPU time and thermal state are the proxies.\n"148 return out149 }150151 /// One table for results of the same family. Timing columns are wall-clock time per operation;152 /// "Result" is the headline figure derived from the median; "CPU / op" is user + system CPU time153 /// of the whole process per operation and "CPU load" its ratio to wall-clock time.154 public static func table(_ results: [BenchmarkResult]) -> String {155 let withSizes = results.contains { $0.sizes != nil }156 var out = "| Benchmark | Result | Median | Mean | Min | p95 | Std dev | Iterations | CPU / op | CPU load | Peak RSS Δ (approx.) |"157 out += withSizes ? " PK / SK / output (bytes) |\n" : "\n"158 out += "|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|"159 out += withSizes ? "---:|\n" : "\n"160 for r in results {161 let s = r.statistics162 var row = "| \(r.displayName) | \(r.headline) | \(BenchmarkFormat.duration(s.median)) | \(BenchmarkFormat.duration(s.mean))"163 row += " | \(BenchmarkFormat.duration(s.min)) | \(BenchmarkFormat.duration(s.p95)) | \(BenchmarkFormat.duration(s.standardDeviation))"164 row += " | \(r.iterations) | \(BenchmarkFormat.duration(r.cpuTimePerOperation)) | \(BenchmarkFormat.number(r.cpuUtilization))× | \(BenchmarkFormat.memory(r.peakResidentIncrease)) |"165 if withSizes {166 if let z = r.sizes {167 let parts = [z.publicKey, z.privateKey, z.output].map { $0.map(String.init) ?? "–" }168 row += " \(parts.joined(separator: " / ")) |"169 } else {170 row += " – |"171 }172 }173 out += row + "\n"174 }175 return out176 }177178 /// Size table of all KEM and signature parameter sets.179 public static func sizeTable(_ sizes: [ParameterSetSizes] = BenchmarkCatalogue.sizeTable) -> String {180 var out = "| Parameter set | Standard | Kind | NIST category | Public key | Private key | Ciphertext / signature | Shared secret |\n"181 out += "|---|---|---|---:|---:|---:|---:|---:|\n"182 for s in sizes {183 out += "| \(s.name) | \(s.standard) | \(s.kind) | \(s.category.map(String.init) ?? "–") | \(s.publicKey) | \(s.privateKey)"184 out += " | \(s.output) | \(s.sharedSecret.map(String.init) ?? "–") |\n"185 }186 return out187 }188}189