Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Charting/ChartBench.swift3// Description: DEBUG-only benchmark of the chart renderer (docs/CHART_PERFORMANCE.md): synthetic series of 10 000 to 100 000 bars, frame cost of zoom and pan steps on screen and of a full off-screen redraw, memory. Never part of a Release build; the synthetic bars are never shown as data.4#if DEBUG5import SwiftUI6import VQuantCore78/// Draw-closure timings, collected only while a benchmark runs.9enum ChartPerf { nonisolated(unsafe) static var samples: [Double]? }1011/// `-VQSection charting -VQXChartBench 10000,20000,50000 [-VQXChartBenchOut /tmp/bench.json] [-VQXChartBenchSizes 1000x640,1728x1000]`12///13/// What is measured, per scenario, over `frames` consecutive display-link ticks, each of which changes the visible14/// window (so the whole chart is redrawn every frame):15/// - `main`: time the main run loop was busy between two ticks — SwiftUI update, the Canvas draw closure, and the16/// Core Animation commit. This is the cost that decides whether a frame is missed.17/// - `closure`: time inside `ChartCanvas.draw` alone (building the paths and issuing the drawing commands).18/// - `interval`: time between two delivered ticks (the display period when no frame is missed).19/// - `cpu`: process CPU time (all threads, so off-main rasterisation is included) per frame.20/// Plus `offscreen`: a full redraw through `ImageRenderer` into a bitmap of the given pixel size (CPU rasterisation).21@MainActor enum ChartBench {22 struct Stat: Codable { var median: Double, p95: Double, worst: Double }23 struct Row: Codable {24 var bars: Int, width: Int, height: Int, scenario: String, indicators: Bool, drawings: Int, visible: Int25 var main: Stat, closure: Stat, interval: Stat26 var cpuPerFrame: Double, missed: Int, frames: Int, refresh: Double27 }28 struct Offscreen: Codable { var bars: Int, width: Int, height: Int, scale: Double, indicators: Bool, drawings: Int, ms: Stat }29 struct Memory: Codable { var bars: Int, footprintBeforeMB: Double, footprintLoadedMB: Double, footprintAfterRunMB: Double }30 struct Report: Codable { var renderer: String, machine: String, os: String, screen: String, rows: [Row], offscreen: [Offscreen], memory: [Memory] }3132 static var started = false3334 static func stat(_ xs: [Double]) -> Stat {35 guard !xs.isEmpty else { return Stat(median: 0, p95: 0, worst: 0) }36 let s = xs.sorted()37 func q(_ p: Double) -> Double { s[min(s.count - 1, Int((Double(s.count - 1) * p).rounded()))] }38 func ms(_ v: Double) -> Double { (v * 1000 * 100).rounded() / 100 }39 return Stat(median: ms(q(0.5)), p95: ms(q(0.95)), worst: ms(s[s.count - 1]))40 }4142 /// A seeded geometric random walk with intrabar extremes, one bar per minute. Deterministic.43 static func synthetic(_ n: Int) -> [Bar] {44 var state: UInt64 = 0x9E3779B97F4A7C1545 func rnd() -> Double { state = state &* 6364136223846793005 &+ 1442695040888963407; return Double(state >> 11) / Double(1 << 53) }46 var out: [Bar] = []; out.reserveCapacity(n)47 var p = 100.048 let t0 = 1_700_000_000.049 for i in 0..<n {50 let o = p51 let c = max(1, o * (1 + (rnd() - 0.5) * 0.012))52 let h = max(o, c) * (1 + rnd() * 0.004), l = min(o, c) * (1 - rnd() * 0.004)53 out.append(Bar(time: Date(timeIntervalSince1970: t0 + Double(i) * 60), open: o, high: h, low: l, close: c, volume: 1000 + rnd() * 90_000))54 p = c55 }56 return out57 }5859 static func footprintMB() -> Double {60 var info = task_vm_info_data_t()61 var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)62 let kr = withUnsafeMutablePointer(to: &info) { $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) } }63 return kr == KERN_SUCCESS ? (Double(info.phys_footprint) / 1_048_576 * 10).rounded() / 10 : 064 }65 static func cpuSeconds() -> Double {66 var u = rusage(); getrusage(RUSAGE_SELF, &u)67 return Double(u.ru_utime.tv_sec) + Double(u.ru_utime.tv_usec) / 1e6 + Double(u.ru_stime.tv_sec) + Double(u.ru_stime.tv_usec) / 1e668 }6970 /// Drives one scenario from the display link and reports when it has seen `frames` ticks.71 final class Driver: NSObject {72 var step: (Int) -> Void = { _ in }73 var done: (() -> Void)?74 var frames = 0, target = 075 var intervals: [Double] = [], busy: [Double] = []76 var lastStamp: CFTimeInterval = 0, period: Double = 077 var busyAccum = 0.0, wake: CFTimeInterval = 078 var observer: CFRunLoopObserver?79 var link: CADisplayLink?8081 func start(in view: NSView, frames: Int) {82 target = frames; self.frames = -10 // warm-up ticks are not recorded83 wake = CACurrentMediaTime()84 observer = CFRunLoopObserverCreateWithHandler(nil, CFRunLoopActivity.beforeWaiting.rawValue | CFRunLoopActivity.afterWaiting.rawValue, true, 0) { [unowned self] _, activity in85 let now = CACurrentMediaTime()86 if activity == .afterWaiting { self.wake = now } else { self.busyAccum += now - self.wake; self.wake = now }87 }88 CFRunLoopAddObserver(CFRunLoopGetMain(), observer, .commonModes)89 let l = view.displayLink(target: self, selector: #selector(tick(_:)))90 l.add(to: .main, forMode: .common); link = l91 }92 @objc func tick(_ l: CADisplayLink) {93 period = l.targetTimestamp - l.timestamp94 let now = CACurrentMediaTime()95 // the work of the previous frame: everything the run loop did since the previous tick, up to this one96 let work = busyAccum + (now - wake); busyAccum = 0; wake = now97 if frames > 0 { intervals.append(l.timestamp - lastStamp); busy.append(work) }98 lastStamp = l.timestamp99 if frames >= target { finish(); return }100 frames += 1101 step(frames)102 }103 func finish() {104 link?.invalidate(); link = nil105 if let observer { CFRunLoopRemoveObserver(CFRunLoopGetMain(), observer, .commonModes) }106 observer = nil107 let d = done; done = nil; d?()108 }109 }110111 static func run(app: AppEnvironment) {112 guard !started, let spec = app.options.extra["ChartBench"] else { return }113 started = true114 Task { await execute(app: app, spec: spec) }115 }116117 private static func execute(app: AppEnvironment, spec: String) async {118 let counts = spec.split(separator: ",").compactMap { Int($0) }.filter { $0 >= 100 }119 let sizes: [(Int, Int)] = (app.options.extra["ChartBenchSizes"] ?? "1000x640,1728x1000").split(separator: ",").compactMap {120 let p = $0.split(separator: "x").compactMap { Int($0) }; return p.count == 2 ? (p[0], p[1]) : nil121 }122 let frames = Int(app.options.extra["ChartBenchFrames"] ?? "") ?? 240123 let withDrawings = ChartBenchHooks.drawingsSupported124 NSLog("VQBENCH start %@", spec)125 try? await Task.sleep(for: .seconds(2))126127 var rows: [Row] = [], off: [Offscreen] = [], mem: [Memory] = []128 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 800, height: 600), styleMask: [.borderless], backing: .buffered, defer: false)129 window.isReleasedWhenClosed = false130 window.level = .normal131 for n in counts {132 let before = footprintMB()133 let bars = synthetic(n)134 let model = ChartModel(app: app, symbol: "BENCH")135 model.benchLoad(bars)136 let loaded = footprintMB()137 for (w, h) in sizes {138 let host = NSHostingView(rootView: ChartCanvas(model: model, settings: app.settings).frame(width: CGFloat(w), height: CGFloat(h)).background(Color(nsColor: .textBackgroundColor)))139 window.setFrame(NSRect(x: 0, y: (NSScreen.main?.visibleFrame.maxY ?? CGFloat(h)) - CGFloat(h), width: CGFloat(w), height: CGFloat(h)), display: true)140 window.contentView = host141 window.orderFrontRegardless()142 for ind in [false, true] {143 model.indicators = ind ? IndicatorSet(sma20: true, sma50: true, sma200: true, ema20: true, bollinger: true, volume: true, rsi: true, macd: true)144 : IndicatorSet(sma20: false, sma50: false, sma200: false, ema20: false, bollinger: false, volume: false, rsi: false, macd: false)145 for nd in (withDrawings ? [0, 50] : [0]) {146 ChartBenchHooks.setDrawings(model, nd)147 // scenario → (visible bars, what a step does)148 let scenarios: [(String, Double, (Int) -> Void)] = [149 ("zoom at full extent", Double(n), { k in model.benchWindow(start: Double(n) * 0.01 * Double(k % 2), count: Double(n) * (k % 2 == 0 ? 1.0 : 0.98)) }),150 ("pan, 2 000 bars visible", 2000, { k in let span = Double(n) - 2000; let ph = Double(k % 120) / 120; model.benchWindow(start: span * (ph < 0.5 ? ph * 2 : (1 - ph) * 2) * 0.2, count: 2000) }),151 ("pan, 200 bars visible", 200, { k in model.benchWindow(start: Double(n) / 2 + Double(k % 100) * 1.5, count: 200) }),152 ]153 for (name, visible, step) in scenarios {154 ChartPerf.samples = []155 let driver = Driver()156 driver.step = step157 let cpu0 = cpuSeconds()158 await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in159 driver.done = { c.resume() }160 driver.start(in: host, frames: frames)161 }162 let cpu = cpuSeconds() - cpu0163 let closure = Array((ChartPerf.samples ?? []).suffix(frames)); ChartPerf.samples = nil164 let period = driver.period > 0 ? driver.period : 1.0 / 120165 rows.append(Row(bars: n, width: w, height: h, scenario: name, indicators: ind, drawings: nd, visible: Int(visible),166 main: stat(driver.busy), closure: stat(closure), interval: stat(driver.intervals),167 cpuPerFrame: (cpu / Double(frames + 10) * 1000 * 100).rounded() / 100,168 missed: driver.intervals.filter { $0 > period * 1.5 }.count, frames: driver.intervals.count, refresh: (1 / period).rounded()))169 }170 }171 }172 }173 // a full redraw into a bitmap (CPU rasterisation), window-sized and 5K-sized174 for (w, h, scale) in [(1000, 640, 2.0), (2560, 1440, 2.0)] {175 for ind in [false, true] {176 for nd in (withDrawings ? [0, 50] : [0]) {177 model.indicators = ind ? IndicatorSet(sma20: true, sma50: true, sma200: true, ema20: true, bollinger: true, volume: true, rsi: true, macd: true)178 : IndicatorSet(sma20: false, sma50: false, sma200: false, ema20: false, bollinger: false, volume: false, rsi: false, macd: false)179 ChartBenchHooks.setDrawings(model, nd)180 model.fit()181 var times: [Double] = []182 for k in 0..<12 {183 model.benchWindow(start: Double(k % 2), count: Double(n))184 let r = ImageRenderer(content: ChartCanvas(model: model, settings: app.settings, interactive: false).frame(width: CGFloat(w), height: CGFloat(h)))185 r.scale = scale186 let t = CACurrentMediaTime(); let img = r.cgImage; let dt = CACurrentMediaTime() - t187 if img != nil, k >= 2 { times.append(dt) }188 }189 off.append(Offscreen(bars: n, width: w, height: h, scale: scale, indicators: ind, drawings: nd, ms: stat(times)))190 }191 }192 }193 NSLog("VQBENCH done %d", n)194 mem.append(Memory(bars: n, footprintBeforeMB: before, footprintLoadedMB: loaded, footprintAfterRunMB: footprintMB()))195 window.contentView = nil196 }197 window.close()198199 var size = 0; sysctlbyname("machdep.cpu.brand_string", nil, &size, nil, 0)200 var name = [UInt8](repeating: 0, count: max(size, 1)); sysctlbyname("machdep.cpu.brand_string", &name, &size, nil, 0)201 let cpu = String(decoding: name.prefix { $0 != 0 }, as: UTF8.self)202 let screen = NSScreen.main.map { "\(Int($0.frame.width))×\(Int($0.frame.height)) pt @\($0.backingScaleFactor)x, up to \($0.maximumFramesPerSecond) Hz" } ?? "?"203 let report = Report(renderer: ChartBenchHooks.rendererName, machine: cpu + ", \(ProcessInfo.processInfo.physicalMemory / 1_073_741_824) GB",204 os: ProcessInfo.processInfo.operatingSystemVersionString, screen: screen, rows: rows, offscreen: off, memory: mem)205 let enc = JSONEncoder(); enc.outputFormatting = [.prettyPrinted, .sortedKeys]206 do {207 let data = try enc.encode(report)208 let path = app.options.extra["ChartBenchOut"] ?? NSTemporaryDirectory() + "vquant-chart-bench.json"209 try data.write(to: URL(fileURLWithPath: (path as NSString).expandingTildeInPath))210 NSLog("VQBENCH written %@", path)211 } catch { NSLog("VQBENCH failed %@", String(describing: error)) }212 NSApp.terminate(nil)213 }214}215#endif216217#if DEBUG218/// What the benchmark needs from the renderer under test.219@MainActor enum ChartBenchHooks {220 static let rendererName = "Core Graphics (SwiftUI Canvas), 2.0 renderer (aligned reduction cached per zoom level)"221 static let drawingsSupported = true222 /// `n` drawings of every kind spread over the series (anchored on its bars).223 static func setDrawings(_ model: ChartModel, _ n: Int) {224 let bars = model.bars225 guard n > 0, bars.count > 100 else { model.benchDrawings([]); return }226 let kinds: [DrawingKind] = [.trend, .hline, .rect, .fib, .text, .measure]227 model.benchDrawings((0..<n).map { k in228 let a = (bars.count - 60) * k / n, b = a + 20 + (k % 5) * 8229 let kind = kinds[k % kinds.count]230 let pa = DrawingPoint(t: model.times[a], p: bars[a].low), pb = DrawingPoint(t: model.times[b], p: bars[b].high)231 return ChartDrawing(id: "bench-\(k)", kind: kind, points: kind.pointsNeeded == 1 ? [pa] : [pa, pb], color: k, text: kind == .text ? "note \(k)" : nil)232 })233 }234}235#endif236