Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668import AppKitimport Foundationimport ParcelAnimationimport ParcelConfigimport ParcelCoreimport QuartzCoreimport Testing
@testable import ParcelAnimation@testable import ParcelEngine@testable import ParcelPlatform@testable import ParcelUI
@MainActorenum HotPathBenchmarks { static func run(_ harness: inout BenchmarkHarness) async throws { try reducerCases(&harness) await Task.yield() try motionCases(&harness) await Task.yield() try inputCases(&harness) await Task.yield() try platformCases(&harness) await Task.yield() try overlayCases(&harness) let tabView = TabViewRenderingFixture() try measure("TabView/CanvasAndCardRaster/12", &harness, latencySamples: 100) { try tabView.render().observation } try await configCases(&harness) try await nativeCases(&harness) try await DisplayEventBenchmarks.run(&harness) try await engineCases(&harness) }
static func writeCatalog() throws { let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() .deletingLastPathComponent().appendingPathComponent("build", isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] try encoder.encode(BenchmarkCatalog.entries).write( to: directory.appendingPathComponent("bench-catalog.json"), options: .atomic) }
private static func measure( _ name: String, _ harness: inout BenchmarkHarness, latencySamples: Int = 1000, operation: () throws -> BenchmarkObservation ) rethrows { let entry = BenchmarkCatalog.definition(named: name) try harness.measure( name, iterations: entry.iterations, reportingOnly: entry.reportingOnly, budget: entry.budget, reason: entry.reason, cpuBudgetNanoseconds: entry.cpuBudgetNanoseconds, latencySamples: latencySamples, operation: operation) }
private static func measureAsync( _ name: String, _ harness: inout BenchmarkHarness, latencySamples: Int = 1000, operation: () async throws -> BenchmarkObservation ) async rethrows { let entry = BenchmarkCatalog.definition(named: name) try await harness.measureAsync( name, iterations: entry.iterations, reportingOnly: entry.reportingOnly, budget: entry.budget, reason: entry.reason, latencySamples: latencySamples, operation: operation) }
private static func reducerCases(_ harness: inout BenchmarkHarness) throws { for count in [10, 50, 200] { for workspaces in [1, 8] { let fixture = HotPathStateFixture(count: count, workspaces: workspaces) guard let target = fixture.activeIDs.last else { throw BenchmarkFailure.measurement("active focus fixture") } measure("reduce.focusObservation.\(count)x\(workspaces)ws", &harness) { let (next, effects) = reduce(fixture.state, .focusChanged(target)) return reduced(next, effects: effects.count) } } let fixture = HotPathStateFixture(count: count) guard let original = fixture.state.frames[fixture.ids[0]], let edge = fixture.state.tileEdges.first else { throw BenchmarkFailure.measurement("interactive fixture geometry") } let drag = Rect( x: original.minX, y: original.minY, width: original.size.width + 8, height: original.size.height) let previousTick = reduce(fixture.state, .windowFrameEdited(fixture.ids[0], frame: drag)).0 measure("reduce.windowFrameEdited.tick.\(count)", &harness) { let (next, effects) = reduce( previousTick, .windowFrameEdited( fixture.ids[0], frame: Rect(x: drag.minX, y: drag.minY, width: drag.size.width + 4, height: drag.size.height))) return reduced(next, effects: effects.count) } measure("reduce.tileEdgeResized.tick.\(count)", &harness) { let (next, effects) = reduce(fixture.state, .tileEdgeResized(edge, delta: 8)) return reduced(next, effects: effects.count) } let pair = (0..<3).map { _ in AsyncStream<EngineSnapshot>.makeStream(bufferingPolicy: .bufferingNewest(1)) } defer { for item in pair { item.continuation.finish() } } measure("snapshot-publish/\(count)", &harness) { let snapshot = EngineSnapshot(revision: 1, state: fixture.state) var yields = 0 for item in pair { switch item.continuation.yield(snapshot) { case .enqueued, .dropped: yields += 1 case .terminated: preconditionFailure("Benchmark snapshot subscriber terminated") @unknown default: preconditionFailure("Unknown stream yield result") } } return BenchmarkObservation( checksum: hotPathChecksum(snapshot.state.frames) + snapshot.tiles.count + yields, proofMetrics: ["subscriber-yields": Double(yields), "snapshot-tiles": Double(snapshot.tiles.count)]) } } for layout in Layout.allCases { let fixture = HotPathStateFixture(count: 10, layout: layout) measure("reduce-layout/\(layout.rawValue)/10", &harness) { let (next, effects) = reduce(fixture.state, .commandIssued(.retile)) return reduced(next, effects: effects.count) } } for count in [50, 200] { let fixture = HotPathStateFixture(count: count) guard let frame = fixture.state.frames[fixture.ids[0]] else { throw BenchmarkFailure.measurement("batch frame") } let burst: [Event] = [ .focusChanged(fixture.ids[1]), .windowMovedByUser(fixture.ids[0], frame: frame), .windowFrameEdited( fixture.ids[0], frame: Rect(x: frame.minX, y: frame.minY, width: frame.size.width + 8, height: frame.size.height)), .focusChanged(fixture.ids[2]), .windowResizedByUser(fixture.ids[1], frame: frame), .commandIssued(.nudgeRatio(0.01)), .focusChanged(fixture.ids[0]), .relayout, ] measure("reduce.batch.mixed8.\(count)", &harness) { let before = hotPathRetainedBytes() let (next, effects) = reduce(fixture.state, burst) var result = reduced(next, effects: effects.reduce(0) { $0 + $1.count }) result.proofMetrics["retained-bytes-delta"] = Double(hotPathRetainedBytes() - before) result.proofMetrics["events-in-batch"] = Double(burst.count) return result } let columns = HotPathStateFixture(count: count, layout: .columns) guard let workspace = columns.state.workspaces[columns.keys[0]], let display = columns.state.displays[columns.keys[0].display] else { throw BenchmarkFailure.measurement("column edge fixture") } measure("layout.edges.columns.\(count)", &harness) { let edges = LayoutEngine.edges(workspace, in: display.frame, windows: columns.state.windows) return BenchmarkObservation( checksum: edges.reduce(1) { $0 + $1.path.count + $1.affectedWindows.count + Int($1.position.rounded()) }, proofMetrics: [ "edges": Double(edges.count), "max-path-depth": Double(edges.map { $0.path.count }.max() ?? 0), ]) } } for layout in [Layout.columns, .rows, .accordion] { let fixture = HotPathStateFixture(count: 200, layout: layout) guard let workspace = fixture.state.workspaces[fixture.keys[0]], let display = fixture.state.displays[fixture.keys[0].display] else { throw BenchmarkFailure.measurement("linear layout fixture") } measure("layout.arrange.\(layout.rawValue).200", &harness) { let layout = LayoutEngine.arrange(workspace, in: display.frame, windows: fixture.state.windows) return BenchmarkObservation( checksum: hotPathChecksum(layout.frames) + layout.visibleWindows.count, proofMetrics: ["arranged-frames": Double(layout.frames.count)]) } } }
private static func reduced(_ state: State, effects: Int) -> BenchmarkObservation { BenchmarkObservation( checksum: hotPathChecksum(state.frames) + effects + Int(state.focusedWindow?.rawValue ?? 0), proofMetrics: [ "windows": Double(state.windows.count), "effects": Double(effects), "undo-entries": Double( state.undoHistory.map { history in history.windows.reduce(0) { $0 + history.count(for: $1) } } ?? 0), ]) }
static func soakTicks(full: Bool) -> Int { full ? 10000 : 30 }
private static func motionCases(_ harness: inout BenchmarkHarness) throws { let counters = harness.counters for count in [1, 10, 30, 200] { let fixture = MotionTickFixture(count: count) let name = count == 200 ? "AnimationTick200" : "motion-tick/\(count)" try measure(name, &harness) { var observation = try fixture.run(counters: counters) observation.counterOperations = 30 return observation } } let soak = MotionTickFixture(count: 30) let ticks = soakTicks(full: harness.full) try measure("motion-soak/30x10000", &harness, latencySamples: 0) { let before = hotPathRetainedBytes() var result = try soak.run(ticks: ticks, counters: counters) result.counterOperations = ticks result.proofMetrics["retained-bytes-after-stop-delta"] = Double(hotPathRetainedBytes() - before) result.proofMetrics["display-source-running-after-stop"] = soak.source.isRunning ? 1 : 0 return result } for count in [10, 200] { let requests = MotionTickFixture(count: count).requests let name = count == 10 ? "motion-retarget/10" : "AnimationSchedule200" try measure(name, &harness) { var animator = Animator() try animator.schedule(requests, at: 100) _ = try animator.tick(at: 100.075) let reversed = requests.map { request in MotionRequest( windowID: request.windowID, appID: request.appID, start: request.start, target: request.start, screen: request.screen) } let cpu = BenchmarkCPUClock.now() let start = ContinuousClock.now let before = try counters.read() try animator.schedule(reversed, at: 100.075) let after = try counters.read() let wall = BenchmarkHarness.nanoseconds(start.duration(to: .now)) let elapsed = BenchmarkCPUClock.elapsed(since: cpu) let measuredCounters: BenchmarkCounterReading? if let before { guard let after else { throw BenchmarkFailure.measurement("retarget counters disappeared") } measuredCounters = try after.delta(from: before) } else { measuredCounters = nil } var checksum = 1 var inheritedSpeed = 0.0 for request in requests { if let sample = try animator.presentation(for: request.windowID, at: 100.075) { checksum += Int(sample.frame.rect.originX.rounded()) + Int(sample.frame.windowID.rawValue) inheritedSpeed += abs(sample.velocity.horizontal) } } return BenchmarkObservation( checksum: checksum, nanoseconds: wall, cpuNanoseconds: elapsed, instructions: measuredCounters.map { Double($0.instructions) }, cycles: measuredCounters.map { Double($0.cycles) }, proofMetrics: [ "retargeted-windows": Double(animator.activeWindowIDs.count), "inherited-speed-sum": inheritedSpeed, ]) } } try measure("CoalescerProMotionJitter", &harness) { try jitter() } try measure("PerWindowRateContinuity", &harness) { var rates: [Double] = [] var snaps = 0 for windows in 1...8 { for microseconds in stride(from: 8000, through: 8600, by: 100) { var metrics = AppWriteMetrics() try metrics.record(duration: Double(microseconds * windows) / 1_000_000, at: 100) rates.append(metrics.frameRate()) if metrics.shouldSnap(at: 100) { snaps += 1 } } } return BenchmarkObservation( checksum: 1 + rates.reduce(0) { $0 + Int($1.rounded()) } + snaps, proofMetrics: [ "rate-at-8.4ms": rates[4], "app-wide-snap-cases": Double(snaps), "minimum-rate": rates.min() ?? 0, "rate-samples": Double(rates.count), ]) } try measure("NeighbourPhaseDivergence", &harness) { try neighbourReplay() } }
static func jitter() throws -> BenchmarkObservation { var coalescer = FrameCoalescer() var dispatches = 0 let window = MotionWindowID(rawValue: 1) let app = MotionAppID(rawValue: 1) for tick in 0..<600 { let timestamp = 100000 + Double(tick) / 120 + (tick % 2 == 0 ? -3e-11 : 3e-11) let request = MotionRequest( windowID: window, appID: app, start: MotionRect(originX: 0, originY: 0, width: 100, height: 100), target: MotionRect(originX: 100, originY: 0, width: 100, height: 100), screen: MotionRect(originX: 0, originY: 0, width: 1000, height: 1000)) let plan = try FramePlanner.plan(request, at: timestamp - 0.01) try coalescer.submit(try plan.sample(at: timestamp).frame) let ready = try coalescer.takeReady(at: timestamp) dispatches += ready.count for batch in ready { try coalescer.complete(batch, duration: 0, at: timestamp) } } return BenchmarkObservation( checksum: dispatches + 1, proofMetrics: ["ticks": 600, "dispatches": Double(dispatches), "skipped-ticks": Double(600 - dispatches)]) }
private static func neighbourReplay() throws -> BenchmarkObservation { var animator = Animator() var coalescer = FrameCoalescer() let screen = MotionRect(originX: 0, originY: 0, width: 1000, height: 1000) let requests: [MotionRequest] = (0..<2).map { index -> MotionRequest in let x = Double(index) * 100 let start = MotionRect(originX: x, originY: 100, width: 100, height: 100) let target = MotionRect(originX: x + 100, originY: 100, width: 100, height: 100) return MotionRequest( windowID: MotionWindowID(rawValue: UInt64(index + 1)), appID: MotionAppID(rawValue: Int32(index + 1)), start: start, target: target, screen: screen) } try animator.schedule(requests, at: 100) var delivered: [MotionWindowID: MotionRect] = Dictionary( uniqueKeysWithValues: requests.map { ($0.windowID, $0.start) }) var inflight: [(batch: FrameBatch, due: Double)] = [] var maximum = 0.0 var overlap = 0.0 var writes = 0 for tick in 1...60 { let time = 100 + Double(tick) / 120 let ready = inflight.filter { $0.due <= time } inflight.removeAll { $0.due <= time } for pending in ready { for frame in pending.batch.frames { delivered[frame.windowID] = frame.rect writes += 1 } try coalescer.complete(pending.batch, duration: pending.due - pending.batch.dispatchedAt, at: time) } for frame in try animator.tick(at: time) { try coalescer.submit(frame) } for batch in try coalescer.takeReady(at: time) { inflight.append((batch, time + (batch.appID.rawValue == 1 ? 0.002 : 0.020))) } guard let left = delivered[requests[0].windowID], let right = delivered[requests[1].windowID] else { throw BenchmarkFailure.measurement("missing neighbour frame") } maximum = max(maximum, abs(left.maxX - right.originX)) overlap = max(overlap, max(0, left.maxX - right.originX) * 100) } return BenchmarkObservation( checksum: writes + Int(maximum.rounded()) + Int(overlap.rounded()) + 1, proofMetrics: [ "maximum-edge-divergence-points": maximum, "maximum-overlap-area": overlap, "delivered-frames": Double(writes), ]) }
private static func inputCases(_ harness: inout BenchmarkHarness) throws { let backend = HotPathKeyBackend() var presses = 0 let center = HotKeyCenter( backend: backend, onPress: { _ in presses += 1 }, onFailure: { Issue.record("Input benchmark failure: \($0)") }) guard let chord = ParcelConfiguration.defaults.keybindings[.focusRight] else { throw BenchmarkFailure.measurement("default synthetic hotkey") } let key = HotKey(keyCode: chord.keyCode, modifiers: .init(rawValue: UInt32(chord.modifiers.rawValue))) // Force the event-tap route without changing the configured default chord. backend.carbonStatus = -1 _ = try center.register(key) defer { do { try center.stop() } catch { Issue.record(error) } } guard let handler = backend.onTapEvent else { throw BenchmarkFailure.measurement("synthetic hotkey handler") } guard let down = CGEvent(keyboardEventSource: nil, virtualKey: key.keyCode, keyDown: true), let up = CGEvent(keyboardEventSource: nil, virtualKey: key.keyCode, keyDown: false), let passthrough = CGEvent(keyboardEventSource: nil, virtualKey: key.keyCode, keyDown: true), let move = CGEvent( mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: CGPoint(x: 20, y: 20), mouseButton: .left) else { throw BenchmarkFailure.measurement("synthetic CGEvent creation") } down.flags = key.modifiers.eventFlags up.flags = key.modifiers.eventFlags passthrough.flags = [] try measure("input-tap/keydown-hotkey", &harness) { let before = presses let consumed = InputEventTap.dispatch(.keyDown, down, handler: handler) _ = InputEventTap.dispatch(.keyUp, up, handler: handler) guard consumed, presses == before + 1 else { throw BenchmarkFailure.measurement("hotkey did not dispatch") } return BenchmarkObservation( checksum: 1, proofMetrics: ["hotkey-press-callbacks": Double(presses - before), "consumed": consumed ? 1 : 0]) } try measure("input-tap/keydown-passthrough", &harness) { let before = presses let consumed = InputEventTap.dispatch(.keyDown, passthrough, handler: handler) center.resetPressedState() guard !consumed, presses == before else { throw BenchmarkFailure.measurement("passthrough consumed") } return BenchmarkObservation(checksum: 1, proofMetrics: ["hotkey-press-callbacks": 0, "consumed": 0]) } let fixture = HotPathStateFixture(count: 10) var mouse = MouseModel() var locations = CGPoint.zero measure("input-tap/mouse-moved", &harness) { var effects: [MouseEffect] = [] let consumed = InputEventTap.dispatch(.mouseMoved, move) { _, event in locations = event.location effects = mouse.reduce( DragSample(kind: .dragged, location: event.location, timestamp: 100), state: fixture.state, configuration: ParcelConfiguration.defaults.mouse) return false } return BenchmarkObservation( checksum: 1 + Int(locations.x + locations.y) + effects.count, proofMetrics: ["mouse-effects": Double(effects.count), "consumed": consumed ? 1 : 0]) } }
private static func platformCases(_ harness: inout BenchmarkHarness) throws { for count in [40, 200] { let fixture = try RecordedWindowFixture(count: count) for name in count == 200 ? ["window-list-read/decode-200", "WindowListDecode/200"] : ["window-list-read/decode-40"] { try measure(name, &harness) { let windows = try fixture.decode() return BenchmarkObservation( checksum: windows.reduce(1) { $0 + Int($1.number) + Int($1.bounds.width.rounded()) + Int($1.layer) }, proofMetrics: ["decoded-windows": Double(windows.count)]) } } } for (name, windows, ticks) in [ ("AXWriteFastPathCalls", 1, 2), ("EnhancedUIToggleCount", 1, 24), ("AppWriteBatch/20", 20, 1), ] { try measure(name, &harness) { try frameWrites(windows: windows, ticks: ticks) } } try measure("FactsReadPerWindow", &harness) { let source = CountingFactsAccess() let facts = try WindowFactsReader.gather( source: source, context: WindowFactsContext(bundleID: "org.example.fixture", activationPolicy: .regular)) return BenchmarkObservation( checksum: source.reads + (facts.isResizable == true ? 1 : 0), proofMetrics: ["fact-access-method-reads": Double(source.reads)]) } let watchdog = AXCallWatchdog(deadline: 1, overdue: { Issue.record("Benchmark watchdog unexpectedly expired") }) defer { watchdog.stop() } measure("WatchdogBeginEnd", &harness) { let token = watchdog.begin() watchdog.end(token) return BenchmarkObservation(checksum: 1) } }
static func frameWrites(windows: Int, ticks: Int) throws -> BenchmarkObservation { let application = CountingFrameAccess(.zero) var calls = 0 var positions = 0 var sizes = 0 var nonFinal = 0 var final = 0 for _ in 0..<windows { let window = CountingFrameAccess(CGRect(x: 0, y: 0, width: 100, height: 100)) for tick in 1...ticks { let before = application.attributeOperations + window.attributeOperations let target = CGRect(x: Double(tick), y: 0, width: 100, height: 100) let actual = try executeFrameWrite( target, window: window, application: application, assistiveTechnology: AssistiveTechnology(voiceOver: false, switchControl: false)) guard actual == target else { throw BenchmarkFailure.measurement("frame write readback") } let count = application.attributeOperations + window.attributeOperations - before if tick == ticks { final += count } else { nonFinal += count } } calls += window.attributeOperations positions += window.positionSets sizes += window.sizeSets } calls += application.attributeOperations return BenchmarkObservation( checksum: calls + positions + sizes + application.enhancedSets, proofMetrics: [ "ax-attribute-operations": Double(calls), "enhanced-ui-sets": Double(application.enhancedSets), "position-sets": Double(positions), "size-sets": Double(sizes), "non-final-attribute-operations": Double(nonFinal), "final-attribute-operations": Double(final), ]) }
private static func configCases(_ harness: inout BenchmarkHarness) async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent( "parcel-config-bench-" + UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) defer { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } } for variant in ["default", "500-rules"] { let source = variant == "default" ? ConfigStore.defaultFileContents : (0..<500).map { index in "[[rules]]\nbundle-id = \"org.example.fixture\(index)\"\ntitle-contains = \"Document \(index)\"\naction = \"float\"\n" }.joined(separator: "\n") let file = directory.appendingPathComponent(variant + ".toml") try Data(source.utf8).write(to: file) let store = ConfigStore(fileURL: file) let initialState = HotPathStateFixture(count: 10).state try await measureAsync("config-reload/\(variant)", &harness) { let snapshot = await store.reload() guard snapshot.loadState == .loaded, snapshot.diagnostics.isEmpty else { throw BenchmarkFailure.measurement("config reload rejected") } let applied = try AppliedConfiguration(snapshot.activeConfiguration) var state = initialState applied.installLayoutDefaults(in: &state) for key in state.workspaces.keys { let display = state.displays[key.display] state.workspaces[key] = applied.workspace( key, in: display?.frame, existing: state.workspaces[key], fullFrame: display?.fullFrame) } return BenchmarkObservation( checksum: snapshot.activeConfiguration.rules.count + state.workspaces.count + snapshot.activeConfiguration.keybindings.count + 1, proofMetrics: [ "loaded-rules": Double(snapshot.activeConfiguration.rules.count), "configured-workspaces": Double(state.workspaces.count), ]) } } }
private static func nativeCases(_ harness: inout BenchmarkHarness) async throws { for count in [10, 50, 200] { let fixture = HotPathNativeFixture(count: count) try await fixture.start() defer { fixture.stop() } try await measureAsync("ax-notify-to-decision/window-moved/\(count)", &harness) { try await fixture.moved() } try await measureAsync("ax-notify-to-decision/window-created/\(count)", &harness) { try await fixture.created() } try await measureAsync("ax-notify-to-decision/focus/\(count)", &harness) { try await fixture.focus() } } let focus = HotPathNativeFixture(count: 50) try await focus.start() defer { focus.stop() } try await measureAsync("FocusFastPath/50", &harness) { try await focus.focus() } try await measureAsync("CreatedToWriteHops", &harness) { try await focus.created(speculate: true) } try await measureAsync("MoveStormCoalesce", &harness, latencySamples: 0) { try await focus.moved(count: 500, cadence: .burst) } try await measureAsync("MoveStormCoalesce/paced", &harness, latencySamples: 0) { try await focus.moved(count: 500, cadence: .paced) } try await measureAsync("EchoReadsDuringGlide", &harness, latencySamples: 0) { try await focus.echoFrames() } let reconcile = HotPathNativeFixture(count: 30, applications: 5) try await reconcile.start() defer { reconcile.stop() } try await measureAsync("SettleReconcileCost", &harness) { try await reconcile.reconcile() } let spaces = HotPathNativeFixture(count: 50, workspaces: 8) try await spaces.start() defer { spaces.stop() } try await measureAsync("SpaceChangeTurn", &harness) { try await spaces.changeSpace() } let hung = HotPathNativeFixture(count: 10, applications: 2) try await hung.start() defer { hung.stop() } try await measureAsync("FocusLatencyWithHungApp", &harness, latencySamples: 0) { try await hung.hungFocus() } }
private static func engineCases(_ harness: inout BenchmarkHarness) async throws { for (count, subscribers, name) in [ (50, 0, "engine.turn.wall.50"), (200, 0, "engine.turn.wall.200"), (50, 1, "engine.snapshot.publish.1subs"), (50, 4, "engine.snapshot.publish.4subs"), ] { let fixture = HotPathStateFixture(count: count) let clock = HotPathClock() let scheduler = HotPathScheduler(clock: clock) let world = HotPathWorld() var configuration = ParcelConfiguration.defaults configuration.motion.enabled = false let engine = try ParcelEngine( world: world, clock: clock, scheduler: scheduler, displayLink: { _ in HotPathEngineLink() }, announcer: HotPathAnnouncer(), log: HotPathLog(), configuration: configuration, initialState: fixture.state, trace: nil, reduceMotionSource: nil) try await engine.start() scheduler.runReady() let streams = (0..<subscribers).map { _ in engine.snapshots() } try await measureAsync(name, &harness) { let before = engine.snapshot.revision let target = engine.snapshot.focusedWindow == fixture.ids[0] ? fixture.ids[1] : fixture.ids[0] engine.send(.focusChanged(target)) scheduler.runReady() guard engine.snapshot.revision > before else { throw BenchmarkFailure.measurement("engine turn not flushed") } return BenchmarkObservation( checksum: hotPathChecksum(engine.snapshot.state.frames) + streams.count, proofMetrics: [ "subscriber-count": Double(streams.count), "windows": Double(engine.snapshot.state.windows.count), ]) } withExtendedLifetime(streams) {} await engine.stop() } }
private static func overlayCases(_ harness: inout BenchmarkHarness) throws { for count in [1, 10, 30] { let fixture = HotPathOverlayFixture(count: count) defer { fixture.stop() } try measure("overlay-update/\(count)", &harness) { try fixture.updatePair() } } let frame = HotPathOverlayFixture(count: 30) defer { frame.stop() } frame.enablePrivacy() measure("overlay-frame/30", &harness) { frame.framePair() } let ghost = HotPathOverlayFixture(count: 50) defer { ghost.stop() } try measure("GhostTransition50", &harness) { try ghost.updatePair(flush: true) } let highlight = HotPathOverlayFixture(count: 10) defer { highlight.stop() } measure("Overlay/HighlightUpdate/10-unchanged", &harness) { highlight.highlight(moved: false) } measure("Overlay/HighlightUpdate/10-moved", &harness) { highlight.highlight(moved: true) } try measure("Overlay/ThemeChange/10-windows", &harness) { try highlight.themePair() } let consume = HotPathOverlayFixture(count: 50) defer { consume.stop() } measure("Overlay/Consume/50-windows", &harness) { consume.consumePair() } measure("Overlay/PrivacyBackdrop/update-8-cutouts", &harness) { highlight.privacyPair() } let chips = StackChipController(focus: { _ in }, close: { _ in }, orderPanels: false) let chipState = HotPathOverlayFixture.chipState() chips.update(state: chipState, configuration: MotionConfiguration(enabled: false)) defer { chips.stop() } measure("Chips/Update/unchanged", &harness) { chips.update(state: chipState, configuration: MotionConfiguration(enabled: false)) precondition(chips.panels.allSatisfy { !$0.isVisible }) return BenchmarkObservation( checksum: chips.groups.count + chips.groups.reduce(0) { $0 + $1.chips.count }, proofMetrics: [ "chip-groups": Double(chips.groups.count), "visible-panels": Double(chips.panels.filter(\.isVisible).count), ]) } let renderer = try MenuIconRenderer() let fixture = HotPathStateFixture(count: 10) let layout = LayoutSnapshot( layout: .grid, bounds: CGRect(x: 0, y: 0, width: 3840, height: 2160), tiles: fixture.ids.map { id in guard let rectangle = fixture.state.frames[id] else { preconditionFailure("Missing icon fixture frame") } return LayoutTile( id: UInt64(id.rawValue), frame: CGRect( x: rectangle.minX, y: rectangle.minY, width: rectangle.size.width, height: rectangle.size.height ), isFocused: id == fixture.ids[0]) }) let icon = MenuIcon(snapshot: layout, style: .minimap) try measure("MenuBar/IconRender", &harness) { guard let bitmap = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: 36, pixelsHigh: 36, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0), let context = NSGraphicsContext(bitmapImageRep: bitmap) else { throw UIResourceError.renderingFailed } NSGraphicsContext.saveGraphicsState() defer { NSGraphicsContext.restoreGraphicsState() } NSGraphicsContext.current = context context.cgContext.scaleBy(x: 2, y: 2) renderer.image(for: icon).draw(in: CGRect(x: 0, y: 0, width: 18, height: 18)) guard let bytes = bitmap.bitmapData else { throw UIResourceError.renderingFailed } let checksum = (0..<bitmap.bytesPerRow * bitmap.pixelsHigh).reduce(1) { $0 + Int(bytes[$1]) } return BenchmarkObservation( checksum: checksum, proofMetrics: ["rasterized-pixels": Double(bitmap.pixelsWide * bitmap.pixelsHigh)]) } }}