SPB Git

Repository Public MIT

Core.swift 6.9 KB 130 lines swift

1// ORIX Calc2// File: Benchmarks/Sources/orix-bench/Core.swift3// Description: Timing harness and the benchmarks of the expression, matrix and workspace engines.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import ORIXExpression9import ORIXWorkspace1011struct Measurement {12    var name: String13    var median: Double      // seconds14    var best: Double15    var runs: Int16    var note: String17}1819nonisolated(unsafe) var results: [Measurement] = []2021/// Runs `body` repeatedly (at least `minRuns` times and `minTime` seconds) and records the median and best wall-clock time.22func measure(_ name: String, note: String = "", minRuns: Int = 7, minTime: Double = 0.25, _ body: () throws -> Void) {23    var samples: [Double] = []24    let clock = ContinuousClock()25    let start = clock.now26    do {27        try body()   // warm-up28        while samples.count < minRuns || (clock.now - start) < .seconds(minTime) {29            let t = clock.now30            try body()31            let d = clock.now - t32            samples.append(Double(d.components.seconds) + Double(d.components.attoseconds) * 1e-18)33            if samples.count >= 2000 { break }34        }35    } catch {36        results.append(Measurement(name: name, median: .nan, best: .nan, runs: 0, note: "FAILED: \(error)"))37        return38    }39    samples.sort()40    results.append(Measurement(name: name, median: samples[samples.count / 2], best: samples[0], runs: samples.count, note: note))41}4243func pretty(_ seconds: Double) -> String {44    if seconds.isNaN { return "—" }45    if seconds < 1e-6 { return String(format: "%.0f ns", seconds * 1e9) }46    if seconds < 1e-3 { return String(format: "%.1f µs", seconds * 1e6) }47    if seconds < 1 { return String(format: "%.2f ms", seconds * 1e3) }48    return String(format: "%.2f s", seconds)49}5051func benchExpression() {52    var engine = CalculatorEngine()53    measure("Parse + evaluate `25 × 4`") { _ = try engine.evaluate("25 × 4") }54    measure("Parse + evaluate `0.1 + 0.2` (exact rational)") { _ = try engine.evaluate("0.1 + 0.2") }55    measure("Parse + evaluate `sin(30)^2 + sqrt(2) * ln(10)`") { _ = try engine.evaluate("sin(30)^2 + sqrt(2) * ln(10)") }56    measure("Full run with explanation and verification `(1234.5 + 6) * 7 / 8 - 9^2`") { _ = try engine.run("(1234.5 + 6) * 7 / 8 - 9^2") }57    measure("`100!` exact (158 digits)") { _ = try engine.evaluate("100!") }58    measure("`2000!` exact (5 736 digits)") { _ = try engine.evaluate("2000!") }59    measure("`sum(1/k^2, k, 1, 1000)` exact rational sum, falls back to double past 8192 bits") { _ = try engine.evaluate("sum(1/k^2, k, 1, 1000)") }60    measure("`integral(exp(-x^2), x, -inf, inf)` adaptive quadrature") { _ = try engine.evaluate("integral(exp(-x^2), x, -inf, inf)") }61    let compiled = try! CompiledExpression(try! Parser.parse("sin(x)^2 + exp(-x/3) * sqrt(abs(x))"), variables: ["x"])62    var sink = 0.063    measure("Compiled function: 100 000 evaluations of sin(x)² + e^(−x/3)·√|x|") {64        for i in 0..<100_000 { sink += compiled(Double(i) * 1e-3) }65    }66    _ = sink6768    func matrix(_ n: Int, exact: Bool) -> String {69        var rows: [String] = []70        for r in 0..<n {71            rows.append((0..<n).map { c in72                let v = ((r * 31 + c * 17) % 23) - 11 + (r == c ? 40 : 0)73                return exact ? "\(v)" : "\(v).5"74            }.joined(separator: ", "))75        }76        return "[" + rows.joined(separator: "; ") + "]"77    }78    _ = try? engine.run("A = " + matrix(20, exact: true).replacingOccurrences(of: ".5", with: ""))79    measure("Determinant 20 × 20, exact rational arithmetic") { _ = try engine.evaluate("det(A)") }80    _ = try? engine.run("E = " + matrix(50, exact: false))81    measure("Determinant 50 × 50, exact rational arithmetic (decimal entries)", minRuns: 5) { _ = try engine.evaluate("det(E)") }82    // pi/pi is a floating-point 1: multiplying by it turns every entry into a double.83    _ = try? engine.run("B = E * (pi/pi)")84    measure("Determinant 50 × 50, floating point") { _ = try engine.evaluate("det(B)") }85    measure("Inverse 50 × 50, floating point (with residual check)") { _ = try engine.evaluate("inv(B)") }86    measure("Product 50 × 50 · 50 × 50, floating point") { _ = try engine.evaluate("B * B") }87    measure("Eigenvalues 50 × 50 (LAPACK dgeev)") { engine.context.complexEnabled = true; _ = try engine.evaluate("eig(B)") }88}8990func benchWorkspace() {91    var cells = [WorkspaceCell.parameter("rate", value: 0.05, range: 0...1, step: 0.01)]92    cells.append(.formula("v0 = 100"))93    for i in 1..<500 { cells.append(.formula("v\(i) = v\(i - 1) * (1 + rate) + \(i % 7)")) }94    let document = WorkspaceDocument(title: "Chain", cells: cells)95    measure("Workspace: open and compute 501 linked cells", minRuns: 5) { _ = WorkspaceEngine(document: document) }96    var engine = WorkspaceEngine(document: document)97    let slider = document.cells[0].id98    var tick = 0.099    measure("Workspace: move a slider that 500 cells depend on", minRuns: 5) {100        tick += 0.001101        engine.setParameter(slider, value: 0.05 + tick.truncatingRemainder(dividingBy: 0.5))102    }103    let last = document.cells.last!.id104    measure("Workspace: edit a leaf cell (1 cell recalculated out of 501)", minRuns: 5) {105        tick += 1106        engine.setSource(last, "v499 = v498 + \(Int(tick))")107    }108    // The same shape with floating-point values: isolates engine overhead from the cost of exact big-number arithmetic.109    var floatCells = [WorkspaceCell.parameter("rate", value: 0.05, range: 0...1, step: 0.01), .formula("w0 = sqrt(2)")]110    for i in 1..<500 { floatCells.append(.formula("w\(i) = sin(w\(i - 1)) + rate * \(i % 7)")) }111    let floatDocument = WorkspaceDocument(title: "Float chain", cells: floatCells)112    var floatEngine = WorkspaceEngine(document: floatDocument)113    measure("Workspace: move a slider that 500 floating-point cells depend on", minRuns: 5) {114        tick += 0.001115        floatEngine.setParameter(floatDocument.cells[0].id, value: 0.05 + tick.truncatingRemainder(dividingBy: 0.5))116    }117    var small = [WorkspaceCell.parameter("DiscountRate", value: 0.08, range: 0...0.3, step: 0.005), .formula("Investment = 100000")]118    for i in 1...10 { small.append(.formula("CashFlow\(i) = \(20000 + i * 1500)")) }119    small.append(.formula("NPV = -Investment + " + (1...10).map { "CashFlow\($0)/(1+DiscountRate)^\($0)" }.joined(separator: " + ")))120    small.append(.formula("Decision = if(NPV > 0, 1, 0)"))121    let smallDocument = WorkspaceDocument(title: "NPV", cells: small)122    var smallEngine = WorkspaceEngine(document: smallDocument)123    measure("Workspace: move the DiscountRate slider of a 14-cell NPV sheet", minRuns: 5) {124        tick += 0.001125        smallEngine.setParameter(smallDocument.cells[0].id, value: 0.01 + tick.truncatingRemainder(dividingBy: 0.25))126    }127    let exporter = WorkspaceExporter(engine: engine)128    measure("Workspace: export 501 cells to LaTeX", minRuns: 5) { _ = exporter.latex() }129}130
Files main
Menu

Theme