Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/SheetEngine/Sources/orix-bench/main.swift10// Module : orix-bench11// Repository : https://git.spboucher.ai/orix-sheet12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import Foundation88import SheetCore89import SheetFormat90import SheetEngine9192// Engine benchmarks. Run in release: swift run -c release orix-bench [--json out.json] [--quick]93// Every number printed is measured on the machine running the tool; nothing is extrapolated.9495ORIXEngine.bootstrap()96let args = CommandLine.arguments97let quick = args.contains("--quick")98let jsonPath = args.firstIndex(of: "--json").flatMap { $0 + 1 < args.count ? args[$0 + 1] : nil }99100@MainActor func time<T>(_ body: () -> T) -> (T, Double) {101 let t0 = DispatchTime.now().uptimeNanoseconds102 let r = body()103 return (r, Double(DispatchTime.now().uptimeNanoseconds - t0) / 1e9)104}105func rssMB() -> Double {106 var info = mach_task_basic_info()107 var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size) / 4108 let kr = withUnsafeMutablePointer(to: &info) { $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count) } }109 return kr == KERN_SUCCESS ? Double(info.resident_size) / 1_048_576 : 0110}111112var results: [[String: Any]] = []113@MainActor func record(_ name: String, _ seconds: Double, _ detail: [String: Any] = [:]) {114 var row: [String: Any] = ["name": name, "seconds": (seconds * 1e6).rounded() / 1e6]115 for (k, v) in detail { row[k] = v }116 results.append(row)117 let extra = detail.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: " ")118 print(String(format: "%-46@ %10.4f s %@", name as NSString, seconds, extra))119}120121/// A sheet of `rows` rows: 4 numeric input columns and `formulaCols` formula columns mixing arithmetic,122/// IF, ROUND, lookups into a small table and a per-row SUM.123func buildModel(rows: Int, formulaCols: Int) -> Workbook {124 let wb = Workbook(sheetNames: ["Model", "Rates"])125 let s = wb.sheets[0], rates = wb.sheets[1]126 for i in 0..<100 { rates.cells.set(row: i, col: 0, Cell(value: .number(Double(i)))); rates.cells.set(row: i, col: 1, Cell(value: .number(1 + Double(i) / 1000))) }127 let templates = ["A{r}*B{r}+C{r}", "IF(D{r}>50,E{r}*1.1,E{r}*0.9)", "ROUND(F{r}/(1+C{r}),2)", "SUM(A{r}:D{r})", "VLOOKUP(MOD(A{r},100),Rates!$A$1:$B$100,2,FALSE)*G{r}",128 "MAX(E{r},F{r},G{r})-MIN(E{r},F{r},G{r})", "IFERROR(H{r}/I{r},0)", "ABS(J{r})^0.5+LN(1+ABS(K{r}))"]129 for r in 0..<rows {130 for c in 0..<4 { s.cells.set(row: r, col: c, Cell(value: .number(Double((r * 31 + c * 17) % 997) / 7))) }131 for k in 0..<formulaCols {132 let text = templates[k % templates.count].replacingOccurrences(of: "{r}", with: String(r + 1))133 s.cells.set(row: r, col: 4 + k, Cell(formula: Formula(expr: try! FormulaParser.parse(text))))134 }135 }136 return wb137}138139print("ORIX Sheet engine benchmark — \(ProcessInfo.processInfo.operatingSystemVersionString), \(ProcessInfo.processInfo.activeProcessorCount) cores, functions: \(ORIXEngine.functionCount)")140#if DEBUG141print("WARNING: debug build — numbers are not representative. Use `swift run -c release orix-bench`.")142#endif143144// 1. parsing145do {146 let n = quick ? 50_000 : 500_000147 let (_, t) = time { for i in 0..<n { _ = try! FormulaParser.parse("IF(SUM(A\(i % 1000 + 1):C\(i % 1000 + 1))>100,VLOOKUP(D1,Sheet2!$A$1:$B$50,2,FALSE)*1.05,\"n/a\")") } }148 record("parse \(n) formulas", t, ["formulasPerSecond": Int(Double(n) / t)])149}150151// 2. full and incremental recalculation at several sizes (total cells = rows × 12)152for rows in quick ? [1_000, 10_000] : [1_000, 10_000, 100_000, 500_000] {153 let cells = rows * 12154 let (wb, tBuild) = time { buildModel(rows: rows, formulaCols: 8) }155 let (engine, tGraph) = time { CalcEngine(workbook: wb) }156 let (stats, tCalc) = time { engine.recalculate() }157 record("build \(cells) cells (\(rows * 8) formulas)", tBuild)158 record("dependency graph, \(rows * 8) formulas", tGraph)159 record("full recalculation, \(rows * 8) formulas", tCalc, ["formulasPerSecond": Int(Double(stats.evaluated) / tCalc), "rssMB": Int(rssMB())])160 engine.set(sheet: 0, row: rows / 2, col: 0, .value(.number(123.456)))161 let (inc, tInc) = time { engine.recalculate() }162 record("incremental recalc after 1 edit (\(rows * 12) cells)", tInc, ["formulasEvaluated": inc.evaluated])163 engine.transaction("edit column") { for r in 0..<rows { engine.set(sheet: 0, row: r, col: 1, .value(.number(Double(r % 13)))) } }164 let (col, tCol) = time { engine.recalculate() }165 record("recalc after editing a whole column (\(rows) edits)", tCol, ["formulasEvaluated": col.evaluated])166}167168// 3. long dependency chain and a wide fan-in169do {170 let n = quick ? 100_000 : 1_000_000171 let wb = Workbook(sheetNames: ["Chain"])172 let s = wb.sheets[0]173 s.cells.set(row: 0, col: 0, Cell(value: .number(1)))174 for r in 1..<n { s.cells.set(row: r, col: 0, Cell(formula: Formula(expr: .binary(.add, .cell(sheet: nil, CellAddr(row: r - 1, col: 0)), .number(1))))) }175 let engine = CalcEngine(workbook: wb)176 let (_, t) = time { engine.recalculate() }177 precondition(s.value(n - 1, 0) == .number(Double(n)))178 record("chain of \(n) dependent formulas", t, ["formulasPerSecond": Int(Double(n) / t)])179 engine.set(sheet: 0, row: 0, col: 0, .value(.number(5)))180 let (_, t2) = time { engine.recalculate() }181 record("chain: change the first cell (\(n) dependents)", t2)182}183do {184 let n = quick ? 200_000 : 1_000_000185 let wb = Workbook(sheetNames: ["Agg"])186 let s = wb.sheets[0]187 for r in 0..<n { s.cells.set(row: r, col: 0, Cell(value: .number(Double(r % 100)))); s.cells.set(row: r, col: 1, Cell(value: .text(["a", "b", "c", "d"][r % 4]))) }188 let engine = CalcEngine(workbook: wb)189 for (i, f) in ["SUM(A:A)", "AVERAGE(A:A)", "COUNTIF(B:B,\"a\")", "SUMIFS(A:A,B:B,\"b\",A:A,\">50\")", "MAX(A:A)-MIN(A:A)", "STDEV.S(A:A)", "MEDIAN(A:A)"].enumerated() {190 engine.setFormula(sheet: 0, row: i, col: 3, f)191 }192 let (_, t) = time { engine.recalculate() }193 record("7 whole-column aggregates over \(n) rows", t)194}195196// 4. number formatting throughput197do {198 let n = quick ? 200_000 : 2_000_000199 let fmt = NumberFormat.cached("#,##0.00")200 var chars = 0201 let (_, t) = time { for i in 0..<n { chars += fmt.render(.number(Double(i) * 1.37)).text.utf8.count } }202 record("format \(n) numbers as #,##0.00", t, ["rendersPerSecond": Int(Double(n) / t)])203 _ = chars204}205206// 5. structural edit and undo on a large sheet207do {208 let rows = quick ? 20_000 : 100_000209 let wb = buildModel(rows: rows, formulaCols: 8)210 let engine = CalcEngine(workbook: wb)211 engine.recalculate()212 let (_, t) = time { engine.insertRows(sheet: 0, at: 10, count: 5); engine.recalculate() }213 record("insert 5 rows + recalc (\(rows * 12) cells)", t)214 let (_, t2) = time { engine.undo(); engine.recalculate() }215 record("undo insert + recalc (\(rows * 12) cells)", t2)216 let (_, t3) = time { engine.sort(sheet: 0, range: RangeRef(r0: 0, c0: 0, r1: rows - 1, c1: 3), keys: [SortKey(column: 0)]) ; engine.recalculate() }217 record("sort \(rows) rows × 4 columns + recalc", t3)218}219220if let jsonPath {221 let payload: [String: Any] = ["date": ISO8601DateFormatter().string(from: Date()), "os": ProcessInfo.processInfo.operatingSystemVersionString,222 "cores": ProcessInfo.processInfo.activeProcessorCount, "memoryGB": Int(ProcessInfo.processInfo.physicalMemory / 1_073_741_824),223 "functions": ORIXEngine.functionCount, "results": results]224 try! JSONSerialization.data(withJSONObject: payload, options: [.prettyPrinted, .sortedKeys]).write(to: URL(fileURLWithPath: jsonPath))225}226