Skip to main content

euv_performance/suite/
fn.rs

1use super::*;
2
3/// Benchmarks fine-grained `Signal` updates propagating through a diamond `Memo` graph.
4///
5/// # Arguments
6///
7/// - `usize` - Number of signal updates to measure.
8///
9/// # Returns
10///
11/// - `BenchMetric` - Measured latency and throughput telemetry.
12#[must_use]
13pub fn bench_reactive_signals_and_memos(iterations: usize) -> BenchMetric {
14    reset_reactive_runtime();
15    let count: usize = iterations.max(1);
16    let source: Signal<i64> = Signal::new(0);
17    let left: Memo<i64> = Memo::new(move || source.get() + 1);
18    let right: Memo<i64> = Memo::new(move || source.get() * 2);
19    let sum: Memo<i64> = Memo::new(move || left.get() + right.get());
20    let start: Instant = Instant::now();
21    let mut checksum: i64 = 0;
22    for i in 1..=(count as i64) {
23        let _: bool = source.set(i);
24        checksum = checksum.wrapping_add(sum.get());
25    }
26    build_metric(
27        BENCH_REACTIVE_NAME,
28        count,
29        start.elapsed(),
30        format!("checksum={checksum}"),
31    )
32}
33
34/// Benchmarks O(1) `Selector<usize>` active-index switching across 1,000 tracked rows.
35///
36/// # Arguments
37///
38/// - `usize` - Number of active-row switches to measure.
39///
40/// # Returns
41///
42/// - `BenchMetric` - Measured latency and throughput telemetry.
43#[must_use]
44pub fn bench_selector_o1(iterations: usize) -> BenchMetric {
45    reset_reactive_runtime();
46    let count: usize = iterations.max(1);
47    let selected: Signal<usize> = Signal::new(0);
48    let selector: Selector<usize> = Selector::new(move || selected.get());
49    let start: Instant = Instant::now();
50    let mut hits: usize = 0;
51    for i in 0..count {
52        let key: usize = i % 1_000;
53        let _: bool = selected.set(key);
54        if selector.is_selected(key) {
55            hits += 1;
56        }
57    }
58    build_metric(
59        BENCH_SELECTOR_NAME,
60        count,
61        start.elapsed(),
62        format!("hits={hits}"),
63    )
64}
65
66/// Benchmarks retained layout engine clean-subtree caching across a 120-node UI tree.
67///
68/// # Arguments
69///
70/// - `usize` - Number of layout passes to measure.
71///
72/// # Returns
73///
74/// - `BenchMetric` - Measured latency and cache-hit telemetry.
75#[must_use]
76pub fn bench_layout_cache(iterations: usize) -> BenchMetric {
77    reset_reactive_runtime();
78    let count: usize = iterations.max(1);
79    let scene: SceneHandle = SceneHandle::new_tree();
80    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
81    let container: NodeId = with_context(ctx, || {
82        view! {
83            column {
84                style: {
85                    width: Length::Px(800.0)
86                    height: Length::Px(600.0)
87                    gap: SPACE_XS
88                }
89                for idx in 0..120usize {
90                    row {
91                        style: {
92                            width: Length::Percent(100.0)
93                            height: Length::Px(24.0)
94                        }
95                        text {
96                            { format!("{BENCH_ROW_LABEL} {idx}") }
97                        }
98                    }
99                }
100            }
101        }
102    });
103    scene.with_write(
104        |tree: &mut SceneTree| {
105            let root: NodeId = tree.get_root();
106            tree.replace_children(root, vec![container]);
107        },
108        (),
109    );
110    let mut engine: LayoutEngine = LayoutEngine::default();
111    let viewport: Size = Size::new(800.0, 600.0);
112    let _: LayoutStats = scene.with_write(
113        |tree: &mut SceneTree| engine.compute(tree, viewport),
114        LayoutStats::default(),
115    );
116    let start: Instant = Instant::now();
117    let mut cache_hits: usize = 0;
118    for _ in 0..count {
119        let stats: LayoutStats = scene.with_write(
120            |tree: &mut SceneTree| engine.compute(tree, viewport),
121            LayoutStats::default(),
122        );
123        cache_hits += stats.get_subtrees_skipped();
124    }
125    build_metric(
126        BENCH_LAYOUT_CACHE_NAME,
127        count,
128        start.elapsed(),
129        format!("cache_hits={cache_hits}"),
130    )
131}
132
133/// Benchmarks full 800x600 software SDF tile rasterization frames.
134///
135/// # Arguments
136///
137/// - `usize` - Number of rendered frames to measure.
138///
139/// # Returns
140///
141/// - `BenchMetric` - Measured frame latency, FPS throughput, and pixel hash.
142#[must_use]
143pub fn bench_software_rasterizer(iterations: usize) -> BenchMetric {
144    bench_render_pipeline(BENCH_SW_RASTER_NAME, RenderConfig::software(), iterations)
145}
146
147/// Benchmarks hardware GPU instanced draw-batch compilation frames.
148///
149/// # Arguments
150///
151/// - `usize` - Number of GPU frame submissions to measure.
152///
153/// # Returns
154///
155/// - `BenchMetric` - Measured frame latency, FPS throughput, and batch count.
156#[must_use]
157pub fn bench_hardware_gpu_batching(iterations: usize) -> BenchMetric {
158    bench_render_pipeline(BENCH_HW_BATCH_NAME, RenderConfig::hardware(), iterations)
159}
160
161/// Benchmarks Unicode + CJK glyph rasterization and GPU RGBA8 atlas shelf-packing.
162///
163/// # Arguments
164///
165/// - `usize` - Number of glyph-pack iterations to measure.
166///
167/// # Returns
168///
169/// - `BenchMetric` - Measured latency and packed glyph count.
170#[must_use]
171pub fn bench_unicode_glyph_atlas(iterations: usize) -> BenchMetric {
172    let count: usize = iterations.max(1);
173    let sample_chars: [char; 8] = ['A', 'g', '9', '跨', '端', '原', '生', '框'];
174    let provider: NativeSystemFont = NativeSystemFont::deterministic();
175    let start: Instant = Instant::now();
176    let mut packed_regions: usize = 0;
177    for _ in 0..count {
178        let mut atlas: GlyphAtlas = GlyphAtlas::default();
179        for ch in sample_chars.iter() {
180            let key: GlyphKey = GlyphKey::new(*ch, 160, false);
181            let _: &RasterizedGlyph = atlas.get_or_rasterize_with(key, &provider);
182        }
183        let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
184        packed_regions = packed.get_regions().len();
185    }
186    build_metric(
187        BENCH_GLYPH_ATLAS_NAME,
188        count,
189        start.elapsed(),
190        format!("packed_glyphs={packed_regions}"),
191    )
192}
193
194/// Benchmarks full forced-redraw 800x600 software SDF tile rasterization frames.
195///
196/// # Arguments
197///
198/// - `usize` - Number of full raster frames to measure.
199///
200/// # Returns
201///
202/// - `BenchMetric` - Measured full-frame raster latency and FPS throughput.
203#[must_use]
204pub fn bench_software_full_redraw(iterations: usize) -> BenchMetric {
205    reset_reactive_runtime();
206    let count: usize = iterations.max(1);
207    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
208    let mut win: WindowConfig = WindowConfig::default();
209    win.set_size(800, 600).set_render(RenderConfig::software());
210    let mut cfg: AppConfig = AppConfig::default();
211    cfg.set_window(win);
212    let Ok(mut app) = App::headless(cfg) else {
213        return build_metric(BENCH_SW_FULL_NAME, count, Duration::ZERO, String::new());
214    };
215    let _: NodeId = app.mount(|| {
216        view! {
217            column {
218                style: {
219                    width: Length::Percent(100.0)
220                    padding: Edges::all(SPACE_LG)
221                    gap: SPACE_MD
222                }
223                EuvHeader {
224                    title: BENCH_TITLE.to_string()
225                    subtitle: BENCH_SUBTITLE.to_string()
226                    tokens: tokens
227                }
228                EuvCard {
229                    title: BENCH_TITLE.to_string()
230                    tokens: tokens
231                    subtitle: BENCH_SUBTITLE
232                    EuvBadge {
233                        label: BENCH_BADGE.to_string()
234                        tone: EuvTone::Primary
235                        tokens: tokens
236                    }
237                    EuvProgress {
238                        value: 0.72
239                        tokens: tokens
240                    }
241                }
242            }
243        }
244    });
245    let wid: WindowId = app.get_window_state().get_id();
246    for _ in 0..BENCH_RENDER_WARMUP_FRAMES {
247        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
248        let _: Result<FrameStats, PlatformError> = app.step_frame();
249    }
250    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
251    let start: Instant = Instant::now();
252    let mut last_hash: u64 = 0;
253    let mut last_batches: usize = 0;
254    for _ in 0..count {
255        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
256        if let Ok(stats) = app.step_frame() {
257            last_hash = stats.get_frame_hash();
258            last_batches = stats.get_draw_batches();
259        }
260    }
261    let elapsed: Duration = start.elapsed();
262    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
263    drop(alloc_guard);
264    assert!(
265        last_batches > 0,
266        "render_software_full_redraw must execute non-zero draw batches"
267    );
268    let denom: f64 = count as f64;
269    build_metric(
270        BENCH_SW_FULL_NAME,
271        count,
272        elapsed,
273        format!(
274            "batches={last_batches} allocs={:.1}/f bytes={:.0}B/f hash={last_hash:#018x}",
275            (alloc_snap.get_alloc_count() as f64) / denom,
276            (alloc_snap.get_bytes_allocated() as f64) / denom,
277        ),
278    )
279    .with_allocations(alloc_snap)
280}
281
282/// Benchmarks 256 dynamic 2D rigid bodies stepping through spatial-hash broad-phase and narrow-phase collision resolution.
283///
284/// # Arguments
285///
286/// - `usize` - Number of fixed 60Hz physics ticks to measure.
287///
288/// # Returns
289///
290/// - `BenchMetric` - Measured physics tick latency and collision throughput.
291#[must_use]
292pub fn bench_game_ecs_physics(iterations: usize) -> BenchMetric {
293    let count: usize = iterations.max(1);
294    let mut world: GameWorld = GameWorld::with_capacity(256);
295    for idx in 0..256usize {
296        let col: f32 = (idx % 16) as f32;
297        let row: f32 = (idx / 16) as f32;
298        let eid: EntityId = world.spawn(
299            EntityTag::Enemy,
300            Point::new(40.0 + col * 52.0, 40.0 + row * 40.0),
301        );
302        if let Some(ent) = world.get_entity_mut(eid) {
303            ent.set_velocity(Velocity2D::new(
304                if idx % 2 == 0 { 110.0 } else { -95.0 },
305                if idx % 3 == 0 { 85.0 } else { -75.0 },
306                0.0,
307            ));
308            ent.set_body(Some(RigidBody2D::dynamic(1.0, 0.9, 0.02)));
309            ent.set_collider(Some(Collider2D::circle(
310                10.0,
311                COLLISION_LAYER_ENEMY,
312                COLLISION_LAYER_ALL,
313                false,
314            )));
315        }
316    }
317    let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
318    phys_cfg.set_arena_bounds(Some(Rect::new(0.0, 0.0, 960.0, 720.0)));
319    let mut physics: PhysicsWorld2D = PhysicsWorld2D::with_config(phys_cfg);
320    for _ in 0..2usize {
321        let _: Vec<CollisionEvent> = physics.step(&mut world, 1.0 / 60.0);
322    }
323    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
324    let start: Instant = Instant::now();
325    let mut total_collisions: usize = 0;
326    for _ in 0..count {
327        let evs: Vec<CollisionEvent> = physics.step(&mut world, 1.0 / 60.0);
328        total_collisions += evs.len();
329    }
330    let elapsed: Duration = start.elapsed();
331    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
332    drop(alloc_guard);
333    let denom: f64 = count as f64;
334    build_metric(
335        BENCH_GAME_PHYSICS_NAME,
336        count,
337        elapsed,
338        format!(
339            "entities=256 collisions={total_collisions} allocs={:.1}/f bytes={:.0}B/f",
340            (alloc_snap.get_alloc_count() as f64) / denom,
341            (alloc_snap.get_bytes_allocated() as f64) / denom,
342        ),
343    )
344    .with_allocations(alloc_snap)
345}
346
347/// Benchmarks updating 1,024 continuously replenished zero-allocation pooled particles per frame.
348///
349/// # Arguments
350///
351/// - `usize` - Number of particle update steps to measure.
352///
353/// # Returns
354///
355/// - `BenchMetric` - Measured particle update latency, sustained active count, and allocation telemetry.
356#[must_use]
357pub fn bench_game_particles(iterations: usize) -> BenchMetric {
358    let count: usize = iterations.max(1);
359    let origin: Point = Point::new(400.0, 300.0);
360    let mut system: ParticleSystem = ParticleSystem::with_capacity(BENCH_PARTICLE_TARGET_ACTIVE);
361    let mut cfg: ParticleEmitterConfig = ParticleEmitterConfig::default();
362    cfg.set_min_life(2.0).set_max_life(4.0);
363    system.emit_burst(origin, BENCH_PARTICLE_TARGET_ACTIVE, cfg);
364    for _ in 0..2usize {
365        let warm_live: usize = system.update(1.0 / 60.0);
366        if warm_live < BENCH_PARTICLE_TARGET_ACTIVE {
367            system.emit_burst(origin, BENCH_PARTICLE_TARGET_ACTIVE - warm_live, cfg);
368        }
369    }
370    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
371    let start: Instant = Instant::now();
372    let mut live: usize = system.get_active_count();
373    let mut min_active: usize = live;
374    for _ in 0..count {
375        live = system.update(1.0 / 60.0);
376        if live < BENCH_PARTICLE_TARGET_ACTIVE {
377            system.emit_burst(origin, BENCH_PARTICLE_TARGET_ACTIVE - live, cfg);
378            live = system.get_active_count();
379        }
380        min_active = min_active.min(live);
381    }
382    let elapsed: Duration = start.elapsed();
383    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
384    drop(alloc_guard);
385    assert_eq!(
386        live, BENCH_PARTICLE_TARGET_ACTIVE,
387        "particle benchmark must sustain full active pool without decay"
388    );
389    let denom: f64 = count as f64;
390    build_metric(
391        BENCH_GAME_PARTICLES_NAME,
392        count,
393        elapsed,
394        format!(
395            "active_particles={live} min_active={min_active} allocs={:.1}/f bytes={:.0}B/f",
396            (alloc_snap.get_alloc_count() as f64) / denom,
397            (alloc_snap.get_bytes_allocated() as f64) / denom,
398        ),
399    )
400    .with_allocations(alloc_snap)
401}
402
403/// Applies deterministic throttle and alternating steering inputs so 3D benchmarks animate vehicle and camera motion.
404///
405/// # Arguments
406///
407/// - `&mut InputState` - Mutable game input state updated per frame.
408/// - `usize` - Current simulation frame index.
409fn drive_game3d_camera_input(input: &mut InputState, step: usize) {
410    let wid: WindowId = WindowId::new(1);
411    if step == 0 {
412        input.ingest(&WindowEvent::KeyDown(
413            wid,
414            KeyEvent::new(KeyCode::Character('w'), Modifiers::default(), false),
415        ));
416    }
417    let phase: usize = (step / 15) % 4;
418    match phase {
419        0 => {
420            input.ingest(&WindowEvent::KeyUp(
421                wid,
422                KeyEvent::new(KeyCode::Character('d'), Modifiers::default(), false),
423            ));
424            input.ingest(&WindowEvent::KeyDown(
425                wid,
426                KeyEvent::new(KeyCode::Character('a'), Modifiers::default(), false),
427            ));
428        }
429        2 => {
430            input.ingest(&WindowEvent::KeyUp(
431                wid,
432                KeyEvent::new(KeyCode::Character('a'), Modifiers::default(), false),
433            ));
434            input.ingest(&WindowEvent::KeyDown(
435                wid,
436                KeyEvent::new(KeyCode::Character('d'), Modifiers::default(), false),
437            ));
438        }
439        _ => {
440            input.ingest(&WindowEvent::KeyUp(
441                wid,
442                KeyEvent::new(KeyCode::Character('a'), Modifiers::default(), false),
443            ));
444            input.ingest(&WindowEvent::KeyUp(
445                wid,
446                KeyEvent::new(KeyCode::Character('d'), Modifiers::default(), false),
447            ));
448        }
449    }
450}
451
452/// Benchmarks the AAA 3D open-world PBR + BVH ray-traced shadows and reflections pipeline with warmup and live camera animation.
453///
454/// # Arguments
455///
456/// - `usize` - Number of warmed animated 3D ray-traced frames to measure.
457///
458/// # Returns
459///
460/// - `BenchMetric` - Measured 3D frame latency, triangle throughput, BVH ray count, and allocation telemetry.
461#[must_use]
462pub fn bench_game3d_pbr_bvh_raytrace(iterations: usize) -> BenchMetric {
463    let count: usize = iterations.max(1);
464    let warmup: usize = if count >= 10 {
465        BENCH_GAME3D_WARMUP_ITERS
466    } else {
467        1
468    };
469    let mut world: World3D = World3D::create_open_world_city();
470    world.ensure_bvh();
471    let mut renderer: Renderer3D = Renderer3D::default();
472    let cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::High);
473    let actions: ActionMap = ActionMap::default();
474    let mut input: InputState = InputState::new();
475    for warm_step in 0..warmup {
476        drive_game3d_camera_input(&mut input, warm_step);
477        world.step_simulation(1.0 / 60.0, &input, &actions);
478        world.ensure_bvh();
479        let _: ImageBuffer = renderer.render_world(&mut world, 480, 270, &cfg);
480    }
481    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
482    let start: Instant = Instant::now();
483    let mut last_rays: usize = 0;
484    let mut last_tris: usize = 0;
485    for step in 0..count {
486        drive_game3d_camera_input(&mut input, warmup + step);
487        world.step_simulation(1.0 / 60.0, &input, &actions);
488        world.ensure_bvh();
489        let _: ImageBuffer = renderer.render_world(&mut world, 480, 270, &cfg);
490        let st: RenderStats3D = renderer.get_last_stats();
491        last_rays = st.get_rays_traced();
492        last_tris = st.get_triangles_drawn();
493    }
494    let elapsed: Duration = start.elapsed();
495    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
496    drop(alloc_guard);
497    let denom: f64 = count as f64;
498    build_metric(
499        BENCH_GAME_3D_RT_NAME,
500        count,
501        elapsed,
502        format!(
503            "warmup={warmup} tris={last_tris} rays={last_rays} allocs={:.1}/f bytes={:.0}B/f",
504            (alloc_snap.get_alloc_count() as f64) / denom,
505            (alloc_snap.get_bytes_allocated() as f64) / denom,
506        ),
507    )
508    .with_allocations(alloc_snap)
509}
510
511/// Benchmarks maxed-out `Cinematic` + `FullPathTracedGi` + `125%` scale animated 3D ray tracing after warmup.
512///
513/// # Arguments
514///
515/// - `usize` - Number of warmed animated max-settings 3D frames to measure.
516///
517/// # Returns
518///
519/// - `BenchMetric` - Measured frame latency, FPS throughput, resolution, ray count, and allocation telemetry.
520#[must_use]
521pub fn bench_game3d_cinematic_max_rt(iterations: usize) -> BenchMetric {
522    let count: usize = iterations.max(1);
523    let warmup: usize = if count >= 10 {
524        BENCH_GAME3D_WARMUP_ITERS
525    } else {
526        1
527    };
528    let mut world: World3D = World3D::create_open_world_city();
529    world.ensure_bvh();
530    let mut renderer: Renderer3D = Renderer3D::default();
531    let mut cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::Cinematic);
532    cfg.set_ray_tracing(RayTracingMode::FullPathTracedGi)
533        .set_resolution_scale(1.25);
534    let pool: RenderBufferPool = RenderBufferPool::with_capacity(3);
535    pool.preallocate(1200, 600);
536    let actions: ActionMap = ActionMap::default();
537    let mut input: InputState = InputState::new();
538    let mut fence_id: u64 = 0;
539    for warm_step in 0..warmup {
540        fence_id += 1;
541        drive_game3d_camera_input(&mut input, warm_step);
542        world.step_simulation(1.0 / 60.0, &input, &actions);
543        world.ensure_bvh();
544        if let Some(lease) =
545            renderer.render_world_into_pool(&mut world, 960, 480, &cfg, &pool, fence_id)
546        {
547            lease.submit_in_flight();
548            let _: usize = pool.retire_fence(fence_id);
549        }
550    }
551    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
552    let start: Instant = Instant::now();
553    let mut last_rays: usize = 0;
554    let mut last_w: u32 = 0;
555    let mut last_h: u32 = 0;
556    for step in 0..count {
557        fence_id += 1;
558        drive_game3d_camera_input(&mut input, warmup + step);
559        world.step_simulation(1.0 / 60.0, &input, &actions);
560        world.ensure_bvh();
561        if let Some(lease) =
562            renderer.render_world_into_pool(&mut world, 960, 480, &cfg, &pool, fence_id)
563        {
564            lease.submit_in_flight();
565            let _: usize = pool.retire_fence(fence_id);
566        }
567        let st: RenderStats3D = renderer.get_last_stats();
568        last_rays = st.get_rays_traced();
569        last_w = st.get_render_width();
570        last_h = st.get_render_height();
571    }
572    let elapsed: Duration = start.elapsed();
573    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
574    drop(alloc_guard);
575    let denom: f64 = count as f64;
576    build_metric(
577        BENCH_GAME_3D_MAX_RT_NAME,
578        count,
579        elapsed,
580        format!(
581            "warmup={warmup} res={last_w}x{last_h} rays={last_rays} allocs={:.1}/f bytes={:.0}B/f",
582            (alloc_snap.get_alloc_count() as f64) / denom,
583            (alloc_snap.get_bytes_allocated() as f64) / denom,
584        ),
585    )
586    .with_allocations(alloc_snap)
587}
588
589/// Stress-benchmarks continuous scrolling of a 100,000-row `EuvVirtualList` through full layout and software rasterization.
590///
591/// # Arguments
592///
593/// - `usize` - Number of scrolled frames to measure.
594///
595/// # Returns
596///
597/// - `BenchMetric` - Measured frame latency, throughput, and final virtual scroll offset.
598#[must_use]
599pub fn bench_stress_long_list_100k(iterations: usize) -> BenchMetric {
600    reset_reactive_runtime();
601    let count: usize = iterations.max(1);
602    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
603    let p: ThemePalette = tokens.get_palette();
604    let g: ThemeGeometry = tokens.get_geometry();
605    let mut win: WindowConfig = WindowConfig::default();
606    win.set_size(400, 720).set_render(RenderConfig::software());
607    let mut cfg: AppConfig = AppConfig::default();
608    cfg.set_window(win);
609    let Ok(mut app) = App::headless(cfg) else {
610        return build_metric(
611            BENCH_STRESS_LONG_LIST_NAME,
612            count,
613            Duration::ZERO,
614            String::new(),
615        );
616    };
617    let scroll_y: Signal<f32> = Signal::new(0.0);
618    let _: NodeId = app.mount(|| {
619        let vlist: EuvVirtualList =
620            EuvVirtualList::new(100_000, 36.0, scroll_y, tokens).viewport_height(680.0);
621        vlist.mount_with(move |idx: usize| {
622            view! {
623                row {
624                    style: {
625                        width: Length::Percent(100.0)
626                        height: Length::Px(36.0)
627                        padding: Edges::symmetric(SPACE_XS, SPACE_MD)
628                        align: AlignItems::Center
629                        border: (g.get_border_width(), p.get_border())
630                    }
631                    text {
632                        style: {
633                            font_size: 13.0
634                            color: p.get_foreground()
635                        }
636                        { format!("{BENCH_ROW_LABEL} #{idx}") }
637                    }
638                }
639            }
640        })
641    });
642    let _: Result<FrameStats, PlatformError> = app.step_frame();
643    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
644    let start: Instant = Instant::now();
645    let mut last_shaded: usize = 0;
646    for step in 1..=count {
647        let next_y: f32 = ((step as f32) * 144.0) % 3_500_000.0;
648        let _: bool = scroll_y.set_if_changed(next_y);
649        if let Ok(stats) = app.step_frame() {
650            last_shaded = stats.get_pixels_shaded();
651        }
652    }
653    let elapsed: Duration = start.elapsed();
654    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
655    drop(alloc_guard);
656    let denom: f64 = count as f64;
657    build_metric(
658        BENCH_STRESS_LONG_LIST_NAME,
659        count,
660        elapsed,
661        format!(
662            "rows=100000 scroll_y={:.0}px shaded={last_shaded} allocs={:.1}/f bytes={:.0}B/f",
663            scroll_y.get_untracked(),
664            (alloc_snap.get_alloc_count() as f64) / denom,
665            (alloc_snap.get_bytes_allocated() as f64) / denom,
666        ),
667    )
668    .with_allocations(alloc_snap)
669}
670
671/// Stress-benchmarks a deeply nested 2,000-node Flex/Grid layout tree under repeated full and dirty-subtree layout passes.
672///
673/// # Arguments
674///
675/// - `usize` - Number of layout passes to measure.
676///
677/// # Returns
678///
679/// - `BenchMetric` - Measured per-pass layout latency and node count.
680#[must_use]
681pub fn bench_stress_complex_layout_2000(iterations: usize) -> BenchMetric {
682    reset_reactive_runtime();
683    let count: usize = iterations.max(1);
684    let scene: SceneHandle = SceneHandle::new_tree();
685    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
686    let (leaf_nodes, page): (Vec<NodeId>, NodeId) = with_context(ctx, || {
687        let mut leaves: Vec<NodeId> = Vec::with_capacity(50);
688        let mut sections: Vec<NodeId> = Vec::with_capacity(50);
689        for section_idx in 0..50usize {
690            let mut first_title: NodeId = NodeId::default();
691            let grid_node: NodeId = view! {
692                grid {
693                    style: {
694                        columns: 4
695                        width: Length::Percent(100.0)
696                        gap: SPACE_SM
697                    }
698                    for card_idx in 0..8usize {
699                        column {
700                            style: {
701                                width: Length::Percent(100.0)
702                                padding: Edges::all(SPACE_SM)
703                                gap: SPACE_XS
704                            }
705                            row {
706                                style: {
707                                    width: Length::Percent(100.0)
708                                    justify: JustifyContent::SpaceBetween
709                                }
710                                if card_idx == 0 {
711                                    text {
712                                        node_ref: first_title
713                                        style: {
714                                            font_size: 13.0
715                                        }
716                                        { format!("{BENCH_CELL_LABEL} {section_idx}-{card_idx}") }
717                                    }
718                                } else {
719                                    text {
720                                        style: {
721                                            font_size: 13.0
722                                        }
723                                        { format!("{BENCH_CELL_LABEL} {section_idx}-{card_idx}") }
724                                    }
725                                }
726                                text {
727                                    style: {
728                                        font_size: 11.0
729                                    }
730                                    { format!("{section_idx}") }
731                                }
732                            }
733                        }
734                    }
735                }
736            };
737            leaves.push(first_title);
738            sections.push(grid_node);
739        }
740        let p_node: NodeId = view! {
741            column {
742                style: {
743                    width: Length::Px(1280.0)
744                    padding: Edges::all(SPACE_MD)
745                    gap: SPACE_SM
746                }
747                ..sections
748            }
749        };
750        (leaves, p_node)
751    });
752    scene.with_write(
753        |tree: &mut SceneTree| {
754            let root: NodeId = tree.get_root();
755            tree.replace_children(root, vec![page]);
756        },
757        (),
758    );
759    let mut engine: LayoutEngine = LayoutEngine::default();
760    let viewport: Size = Size::new(1280.0, 800.0);
761    let init_stats: LayoutStats = scene.with_write(
762        |tree: &mut SceneTree| engine.compute(tree, viewport),
763        LayoutStats::default(),
764    );
765    let start: Instant = Instant::now();
766    let mut total_computed: usize = 0;
767    let mut total_skipped: usize = 0;
768    for step in 0..count {
769        let target: NodeId = leaf_nodes[step % leaf_nodes.len()];
770        scene.with_write(
771            |tree: &mut SceneTree| {
772                tree.set_text(target, format!("{BENCH_CELL_LABEL} #{step}"));
773                let stats: LayoutStats = engine.compute(tree, viewport);
774                total_computed += stats.get_nodes_computed();
775                total_skipped += stats.get_subtrees_skipped();
776            },
777            (),
778        );
779    }
780    build_metric(
781        BENCH_STRESS_COMPLEX_LAYOUT_NAME,
782        count,
783        start.elapsed(),
784        format!(
785            "initial_nodes={} avg_computed={} avg_skipped={}",
786            init_stats.get_nodes_computed(),
787            total_computed / count,
788            total_skipped / count
789        ),
790    )
791}
792
793/// Stress-benchmarks bulk batched updates across 1,000 live reactive UI components with subscribed signals and memos.
794///
795/// # Arguments
796///
797/// - `usize` - Number of full 1,000-component batch update ticks to measure.
798///
799/// # Returns
800///
801/// - `BenchMetric` - Measured batch update + reactive flush + scene patch latency.
802#[must_use]
803pub fn bench_stress_bulk_reactive_1000(iterations: usize) -> BenchMetric {
804    reset_reactive_runtime();
805    let count: usize = iterations.max(1);
806    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
807    let p: ThemePalette = tokens.get_palette();
808    let mut win: WindowConfig = WindowConfig::default();
809    win.set_size(800, 600).set_render(RenderConfig::hardware());
810    let mut cfg: AppConfig = AppConfig::default();
811    cfg.set_window(win);
812    let Ok(mut app) = App::headless(cfg) else {
813        return build_metric(
814            BENCH_STRESS_BULK_REACTIVE_NAME,
815            count,
816            Duration::ZERO,
817            String::new(),
818        );
819    };
820    let mut signals: Vec<Signal<u32>> = Vec::with_capacity(1_000);
821    for idx in 0..1_000u32 {
822        signals.push(Signal::new(idx));
823    }
824    let signals_mount: Vec<Signal<u32>> = signals.clone();
825    let _: NodeId = app.mount(move || {
826        let derived_memos: Vec<Memo<u32>> = signals_mount
827            .into_iter()
828            .map(|sig: Signal<u32>| Memo::new(move || sig.get().wrapping_mul(3).wrapping_add(1)))
829            .collect();
830        view! {
831            scroll {
832                style: {
833                    width: Length::Percent(100.0)
834                    height: Length::Percent(100.0)
835                    gap: 2.0
836                }
837                for derived in derived_memos.into_iter() {
838                    text {
839                        style: {
840                            font_size: 12.0
841                            color: p.get_foreground()
842                        }
843                        { move || format!("{BENCH_CELL_LABEL} {}", derived.get()) }
844                    }
845                }
846            }
847        }
848    });
849    let _: Result<FrameStats, PlatformError> = app.step_frame();
850    let start: Instant = Instant::now();
851    let mut last_rev: u64 = 0;
852    for tick in 1..=(count as u32) {
853        batch(|| {
854            for (idx, sig) in signals.iter().enumerate() {
855                let _: bool = sig.set_if_changed(tick.wrapping_add(idx as u32));
856            }
857        });
858        flush_effects();
859        if app.step_frame().is_ok() {
860            last_rev = app.get_last_rendered_revision();
861        }
862    }
863    build_metric(
864        BENCH_STRESS_BULK_REACTIVE_NAME,
865        count,
866        start.elapsed(),
867        format!("components=1000 final_rev={last_rev}"),
868    )
869}
870
871/// Stress-benchmarks end-to-end dynamic `.wasm` binary verification, sandbox execution, hot-swap, and rollback cycles.
872///
873/// # Arguments
874///
875/// - `usize` - Number of v1 -> v2 -> rollback hot-swap cycles to measure.
876///
877/// # Returns
878///
879/// - `BenchMetric` - Measured latency per full dynamic WASM hot-swap cycle.
880#[must_use]
881pub fn bench_stress_wasm_dynamic_hotswap(iterations: usize) -> BenchMetric {
882    reset_reactive_runtime();
883    let count: usize = iterations.max(1);
884    let mut win: WindowConfig = WindowConfig::default();
885    win.set_size(640, 480).set_render(RenderConfig::hardware());
886    let mut cfg: AppConfig = AppConfig::default();
887    cfg.set_window(win);
888    let Ok(mut app) = App::headless(cfg) else {
889        return build_metric(
890            BENCH_STRESS_WASM_LOAD_NAME,
891            count,
892            Duration::ZERO,
893            String::new(),
894        );
895    };
896    let hub: DynamicUpdateHub = app.get_dynamic_hub().clone();
897    let registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
898    let wasm_v1: Vec<u8> = build_partial_widget_wasm(BENCH_WASM_TITLE_V1, 1, 0x2563EB);
899    let wasm_v2: Vec<u8> = build_partial_widget_wasm(BENCH_WASM_TITLE_V2, 2, 0x7C3AED);
900    let csum_v1: u64 = compute_wasm_checksum(&wasm_v1);
901    let csum_v2: u64 = compute_wasm_checksum(&wasm_v2);
902    registry.register(
903        BENCH_WASM_URL_V1.to_string(),
904        wasm_v1,
905        BENCH_WASM_ETAG_V1.to_string(),
906        WasmFaultKind::None,
907    );
908    registry.register(
909        BENCH_WASM_URL_V2.to_string(),
910        wasm_v2,
911        BENCH_WASM_ETAG_V2.to_string(),
912        WasmFaultKind::None,
913    );
914    let manager: WasmDynamicManager =
915        WasmDynamicManager::new(hub.clone(), Rc::new(registry), WasmSandboxConfig::default());
916    let hub_slot: DynamicUpdateHub = hub;
917    let _: NodeId = app.mount(move || {
918        view! {
919            slot {
920                id: BENCH_WASM_SLOT
921                hub: hub_slot
922                text {
923                    style: {
924                        font_size: 14.0
925                    }
926                    { BENCH_TITLE }
927                }
928            }
929        }
930    });
931    let _: Result<FrameStats, PlatformError> = app.step_frame();
932    let start: Instant = Instant::now();
933    let mut completed: usize = 0;
934    for cycle in 0..count {
935        let base_ver: u64 = ((cycle as u64) * 2) + 1;
936        let req_v1: WasmDownloadRequest = WasmDownloadRequest::partial(
937            BENCH_WASM_URL_V1.to_string(),
938            BENCH_WASM_SLOT.to_string(),
939            base_ver,
940        )
941        .with_checksum(csum_v1)
942        .with_allow_downgrade(true);
943        let req_v2: WasmDownloadRequest = WasmDownloadRequest::partial(
944            BENCH_WASM_URL_V2.to_string(),
945            BENCH_WASM_SLOT.to_string(),
946            base_ver + 1,
947        )
948        .with_checksum(csum_v2)
949        .with_allow_downgrade(true);
950        if manager.load_and_mount(req_v1, BENCH_WASM_SIGN_KEY).is_ok()
951            && manager.load_and_mount(req_v2, BENCH_WASM_SIGN_KEY).is_ok()
952            && manager
953                .rollback_partial(BENCH_WASM_SLOT, BENCH_WASM_ROLLBACK_REASON)
954                .is_ok()
955        {
956            let _: Result<FrameStats, PlatformError> = app.step_frame();
957            completed += 1;
958        }
959    }
960    build_metric(
961        BENCH_STRESS_WASM_LOAD_NAME,
962        count,
963        start.elapsed(),
964        format!("cycles={completed} cache={}", manager.cache_len()),
965    )
966}
967
968/// Stress-benchmarks flagship mobile `1440x3168 @ 4.0x` multi-card shadowed UI scrolling in the multi-core software rasterizer.
969///
970/// # Arguments
971///
972/// - `usize` - Number of full scrolled 4x-DPI frames to measure.
973///
974/// # Returns
975///
976/// - `BenchMetric` - Measured frame latency and FPS throughput at `1440x3168`.
977#[must_use]
978pub fn bench_stress_hidpi_4x_1440x3168(iterations: usize) -> BenchMetric {
979    reset_reactive_runtime();
980    let count: usize = iterations.max(1);
981    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
982    let mut win: WindowConfig = WindowConfig::default();
983    win.set_size(360, 792).set_render(RenderConfig::software());
984    let mut cfg: AppConfig = AppConfig::default();
985    cfg.set_window(win);
986    let Ok(mut app) = App::headless(cfg) else {
987        return build_metric(
988            BENCH_STRESS_HIDPI_4X_NAME,
989            count,
990            Duration::ZERO,
991            String::new(),
992        );
993    };
994    let mut scroll_id: NodeId = NodeId::default();
995    let _: NodeId = app.mount(|| {
996        view! {
997            scroll {
998                node_ref: scroll_id
999                style: {
1000                    width: Length::Percent(100.0)
1001                    height: Length::Percent(100.0)
1002                    padding: Edges::all(SPACE_MD)
1003                    gap: SPACE_MD
1004                    background: tokens.get_palette().get_background()
1005                }
1006                for idx in 0..16usize {
1007                    EuvCard {
1008                        title: format!("{BENCH_TITLE} #{idx}")
1009                        tokens: tokens
1010                        subtitle: BENCH_CARD_CAPTION
1011                        EuvBadge {
1012                            label: BENCH_BADGE.to_string()
1013                            tone: EuvTone::Primary
1014                            tokens: tokens
1015                        }
1016                        EuvProgress {
1017                            value: ((idx % 9) as f32 + 1.0) * 0.1
1018                            tokens: tokens
1019                        }
1020                    }
1021                }
1022            }
1023        }
1024    });
1025    app.set_exact_physical_viewport(1440, 3168, 4.0);
1026    let _: Result<FrameStats, PlatformError> = app.step_frame();
1027    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
1028    let start: Instant = Instant::now();
1029    let mut last_shaded: usize = 0;
1030    for step in 1..=count {
1031        let offset_y: f32 = ((step as f32) * 18.5) % 800.0;
1032        app.get_scene().with_write(
1033            |tree: &mut SceneTree| {
1034                tree.set_scroll_offset(scroll_id, Point::new(0.0, offset_y));
1035            },
1036            (),
1037        );
1038        if let Ok(stats) = app.step_frame() {
1039            last_shaded = stats.get_pixels_shaded();
1040        }
1041    }
1042    let elapsed: Duration = start.elapsed();
1043    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
1044    drop(alloc_guard);
1045    let denom: f64 = count as f64;
1046    build_metric(
1047        BENCH_STRESS_HIDPI_4X_NAME,
1048        count,
1049        elapsed,
1050        format!(
1051            "res=1440x3168@4x shaded={last_shaded} allocs={:.1}/f bytes={:.0}B/f",
1052            (alloc_snap.get_alloc_count() as f64) / denom,
1053            (alloc_snap.get_bytes_allocated() as f64) / denom,
1054        ),
1055    )
1056    .with_allocations(alloc_snap)
1057}
1058
1059/// Stress-benchmarks 240Hz touch-pan scroll physics, thumb-lift anti-reversal filtering, and 1,000-node scene hit-testing.
1060///
1061/// # Arguments
1062///
1063/// - `usize` - Number of 240Hz input/hit-test ticks to measure.
1064///
1065/// # Returns
1066///
1067/// - `BenchMetric` - Measured input + hit-test latency and throughput.
1068#[must_use]
1069pub fn bench_stress_scroll_physics_and_hittest(iterations: usize) -> BenchMetric {
1070    reset_reactive_runtime();
1071    let count: usize = iterations.max(1);
1072    let mut win: WindowConfig = WindowConfig::default();
1073    win.set_size(360, 792).set_render(RenderConfig::hardware());
1074    let mut cfg: AppConfig = AppConfig::default();
1075    cfg.set_window(win);
1076    let Ok(mut app) = App::headless(cfg) else {
1077        return build_metric(
1078            BENCH_STRESS_INPUT_HITTEST_NAME,
1079            count,
1080            Duration::ZERO,
1081            String::new(),
1082        );
1083    };
1084    let _: NodeId = app.mount(|| {
1085        view! {
1086            scroll {
1087                style: {
1088                    width: Length::Percent(100.0)
1089                    height: Length::Percent(100.0)
1090                    gap: 4.0
1091                }
1092                for idx in 0..1_000usize {
1093                    row {
1094                        style: {
1095                            width: Length::Percent(100.0)
1096                            height: Length::Px(32.0)
1097                            cursor: CursorIcon::Pointer
1098                        }
1099                        text {
1100                            { format!("{BENCH_ROW_LABEL} {idx}") }
1101                        }
1102                    }
1103                }
1104            }
1105        }
1106    });
1107    let wid: WindowId = app.get_window_state().get_id();
1108    let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 120.0);
1109    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
1110    let start: Instant = Instant::now();
1111    let mut hits: usize = 0;
1112    app.dispatch_window_event(WindowEvent::PointerDown(
1113        wid,
1114        PointerEvent::touch(1, 180.0, 620.0),
1115    ));
1116    for step in 0..count {
1117        let y: f32 = 620.0 - ((step % 48) as f32) * 8.0;
1118        app.dispatch_window_event(WindowEvent::PointerMove(
1119            wid,
1120            PointerEvent::touch(1, 180.0, y),
1121        ));
1122        let found: bool = app.get_scene().with_read(
1123            |tree: &SceneTree| hit_test(tree, Point::new(180.0, 320.0)).is_some(),
1124            false,
1125        );
1126        if found {
1127            hits += 1;
1128        }
1129        if step % 2 == 0 {
1130            let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
1131        }
1132    }
1133    app.dispatch_window_event(WindowEvent::PointerUp(
1134        wid,
1135        PointerEvent::touch(1, 180.0, 240.0),
1136    ));
1137    let elapsed: Duration = start.elapsed();
1138    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
1139    drop(alloc_guard);
1140    let denom: f64 = count as f64;
1141    build_metric(
1142        BENCH_STRESS_INPUT_HITTEST_NAME,
1143        count,
1144        elapsed,
1145        format!(
1146            "nodes=1000 hits={hits} allocs={:.1}/f bytes={:.0}B/f",
1147            (alloc_snap.get_alloc_count() as f64) / denom,
1148            (alloc_snap.get_bytes_allocated() as f64) / denom,
1149        ),
1150    )
1151    .with_allocations(alloc_snap)
1152}
1153
1154/// Benchmarks forced 800x600 software redraw of 12 `Overflow::Hidden` rounded cards with borders, shadows, badges, progress bars, and wrapped text.
1155///
1156/// # Arguments
1157///
1158/// - `usize` - Number of full software redraw frames to measure.
1159///
1160/// # Returns
1161///
1162/// - `BenchMetric` - Measured frame latency, throughput, and pixel hash.
1163#[must_use]
1164pub fn bench_software_rounded_clip_cards(iterations: usize) -> BenchMetric {
1165    reset_reactive_runtime();
1166    let count: usize = iterations.max(1);
1167    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1168    let p: ThemePalette = tokens.get_palette();
1169    let g: ThemeGeometry = tokens.get_geometry();
1170    let mut win: WindowConfig = WindowConfig::default();
1171    win.set_size(800, 600).set_render(RenderConfig::software());
1172    let mut cfg: AppConfig = AppConfig::default();
1173    cfg.set_window(win);
1174    let Ok(mut app) = App::headless(cfg) else {
1175        return build_metric(
1176            BENCH_SW_ROUNDED_CLIP_NAME,
1177            count,
1178            Duration::ZERO,
1179            String::new(),
1180        );
1181    };
1182    let _: NodeId = app.mount(|| {
1183        view! {
1184            grid {
1185                style: {
1186                    columns: 3
1187                    width: Length::Percent(100.0)
1188                    height: Length::Percent(100.0)
1189                    padding: Edges::all(SPACE_SM)
1190                    gap: SPACE_SM
1191                    background: p.get_background()
1192                }
1193                for idx in 0..12usize {
1194                    column {
1195                        style: {
1196                            width: Length::Percent(100.0)
1197                            padding: Edges::all(SPACE_SM)
1198                            gap: SPACE_XS
1199                            background: p.get_card()
1200                            border: (g.get_border_width(), p.get_border())
1201                            radius: 16.0
1202                            shadow: g.get_shadow_md()
1203                            overflow: Overflow::Hidden
1204                        }
1205                        row {
1206                            style: {
1207                                width: Length::Percent(100.0)
1208                                justify: JustifyContent::SpaceBetween
1209                                align: AlignItems::Center
1210                            }
1211                            text {
1212                                style: {
1213                                    flex_shrink: 1.0
1214                                    min_width: Length::Px(0.0)
1215                                    font_size: 13.0
1216                                    font_weight: FontWeight::SemiBold
1217                                    color: p.get_card_foreground()
1218                                }
1219                                { format!("{BENCH_TITLE} #{idx}") }
1220                            }
1221                            EuvBadge {
1222                                label: BENCH_BADGE.to_string()
1223                                tone: if idx % 2 == 0 { EuvTone::Primary } else { EuvTone::Success }
1224                                tokens: tokens
1225                            }
1226                        }
1227                        text {
1228                            style: {
1229                                width: Length::Percent(100.0)
1230                                font_size: 11.0
1231                                color: p.get_muted_foreground()
1232                            }
1233                            { BENCH_CARD_WRAP_COPY }
1234                        }
1235                        EuvProgress {
1236                            value: ((idx % 8) as f32 + 1.0) * 0.11
1237                            tokens: tokens
1238                        }
1239                    }
1240                }
1241            }
1242        }
1243    });
1244    let wid: WindowId = app.get_window_state().get_id();
1245    let _: Result<FrameStats, PlatformError> = app.step_frame();
1246    let start: Instant = Instant::now();
1247    let mut last_hash: u64 = 0;
1248    let mut last_shaded: usize = 0;
1249    for _ in 0..count {
1250        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
1251        if let Ok(stats) = app.step_frame() {
1252            last_hash = stats.get_frame_hash();
1253            last_shaded = stats.get_pixels_shaded();
1254        }
1255    }
1256    build_metric(
1257        BENCH_SW_ROUNDED_CLIP_NAME,
1258        count,
1259        start.elapsed(),
1260        format!("cards=12 shaded={last_shaded} hash={last_hash:#018x}"),
1261    )
1262}
1263
1264/// Benchmarks forced 800x600 software redraw of linear gradients, 1:1 & scaled rounded images, sprite regions, circles, thick AA lines, and filled triangles.
1265///
1266/// # Arguments
1267///
1268/// - `usize` - Number of full software redraw frames to measure.
1269///
1270/// # Returns
1271///
1272/// - `BenchMetric` - Measured frame latency, throughput, and pixel hash.
1273#[must_use]
1274pub fn bench_software_primitives_image_vec(iterations: usize) -> BenchMetric {
1275    reset_reactive_runtime();
1276    let count: usize = iterations.max(1);
1277    let mut win: WindowConfig = WindowConfig::default();
1278    win.set_size(800, 600).set_render(RenderConfig::software());
1279    let mut cfg: AppConfig = AppConfig::default();
1280    cfg.set_window(win);
1281    let Ok(mut app) = App::headless(cfg) else {
1282        return build_metric(
1283            BENCH_SW_PRIMITIVES_NAME,
1284            count,
1285            Duration::ZERO,
1286            String::new(),
1287        );
1288    };
1289    let img_opaque: ImageBuffer = build_test_image_buffer(128, 128, 255);
1290    let img_rounded: ImageBuffer = build_test_image_buffer(96, 96, 224);
1291    let sprite_sheet: ImageBuffer = build_test_image_buffer(128, 128, 255);
1292    let img_canvas_opaque: ImageBuffer = img_opaque.clone();
1293    let img_canvas_scaled: ImageBuffer = img_rounded.clone();
1294    let canvas_sprites: ImageBuffer = sprite_sheet;
1295    let _: NodeId = app.mount(move || {
1296        let painter = move |bounds: Rect, dl: &mut DisplayList| {
1297            let bx: f32 = bounds.get_x();
1298            let by: f32 = bounds.get_y();
1299            dl.push(DrawCommand::LinearGradientRect {
1300                rect: Rect::new(bx + 8.0, by + 8.0, 240.0, 110.0),
1301                gradient: LinearGradient::new(
1302                    0.0,
1303                    Color::rgb(37, 99, 235),
1304                    Color::rgb(124, 58, 237),
1305                ),
1306                radius: CornerRadius::all(14.0),
1307            });
1308            dl.push(DrawCommand::LinearGradientRect {
1309                rect: Rect::new(bx + 260.0, by + 8.0, 240.0, 110.0),
1310                gradient: LinearGradient::new(
1311                    45.0,
1312                    Color::rgb(16, 185, 129),
1313                    Color::rgb(14, 165, 233),
1314                ),
1315                radius: CornerRadius::all(14.0),
1316            });
1317            dl.push(DrawCommand::Image {
1318                rect: Rect::new(bx + 516.0, by + 8.0, 128.0, 128.0),
1319                buffer: img_canvas_opaque.clone(),
1320                radius: CornerRadius::all(0.0),
1321            });
1322            dl.push(DrawCommand::Image {
1323                rect: Rect::new(bx + 654.0, by + 8.0, 130.0, 116.0),
1324                buffer: img_canvas_scaled.clone(),
1325                radius: CornerRadius::all(18.0),
1326            });
1327            for idx in 0..8usize {
1328                let fx: f32 = bx + 12.0 + (idx as f32) * 94.0;
1329                let tint: Color = if idx % 2 == 0 {
1330                    Color::rgb(255, 255, 255)
1331                } else {
1332                    Color::rgba(220, 235, 255, 220)
1333                };
1334                dl.push(DrawCommand::SpriteRegion {
1335                    rect: Rect::new(fx, by + 150.0, 76.0, 64.0),
1336                    buffer: canvas_sprites.clone(),
1337                    src_rect: Rect::new(
1338                        ((idx % 4) as f32) * 32.0,
1339                        ((idx / 4) as f32) * 64.0,
1340                        32.0,
1341                        64.0,
1342                    ),
1343                    tint,
1344                });
1345            }
1346            for idx in 0..12usize {
1347                let cx: f32 = bx + 42.0 + (idx as f32) * 62.0;
1348                let cy: f32 = by + 258.0 + ((idx % 2) as f32) * 26.0;
1349                dl.push(DrawCommand::Circle {
1350                    center: Point::new(cx, cy),
1351                    radius: 14.0 + ((idx % 4) as f32) * 4.0,
1352                    color: Color::rgba(59 + ((idx as u8) * 14), 130, 246 - ((idx as u8) * 12), 235),
1353                });
1354            }
1355            for idx in 0..16usize {
1356                let lx: f32 = bx + 16.0 + (idx as f32) * 46.0;
1357                dl.push(DrawCommand::Line {
1358                    from: Point::new(lx, by + 312.0),
1359                    to: Point::new(lx + 72.0, by + 372.0),
1360                    color: Color::rgba(244, 63, 94, 230),
1361                    width: 2.5 + ((idx % 3) as f32) * 1.5,
1362                });
1363            }
1364            for idx in 0..12usize {
1365                let tx: f32 = bx + 18.0 + (idx as f32) * 62.0;
1366                let ty: f32 = by + 392.0;
1367                let (p0, p1, p2): (Point, Point, Point) = if idx % 2 == 0 {
1368                    (
1369                        Point::new(tx, ty + 48.0),
1370                        Point::new(tx + 28.0, ty),
1371                        Point::new(tx + 54.0, ty + 48.0),
1372                    )
1373                } else {
1374                    (
1375                        Point::new(tx, ty),
1376                        Point::new(tx + 54.0, ty),
1377                        Point::new(tx + 27.0, ty + 48.0),
1378                    )
1379                };
1380                dl.push(DrawCommand::Triangle {
1381                    p0,
1382                    p1,
1383                    p2,
1384                    color: Color::rgba(234, 179, 8, 225),
1385                });
1386            }
1387        };
1388        view! {
1389            column {
1390                style: {
1391                    width: Length::Percent(100.0)
1392                    height: Length::Percent(100.0)
1393                    padding: Edges::all(SPACE_SM)
1394                    gap: SPACE_SM
1395                    background: Color::rgb(15, 23, 42)
1396                }
1397                row {
1398                    style: {
1399                        width: Length::Percent(100.0)
1400                        height: Length::Px(104.0)
1401                        gap: SPACE_SM
1402                    }
1403                    view {
1404                        style: {
1405                            flex_grow: 1.0
1406                            height: Length::Percent(100.0)
1407                            gradient: LinearGradient::new(
1408                                0.0,
1409                                Color::rgb(30, 64, 175),
1410                                Color::rgb(15, 23, 42),
1411                            )
1412                            radius: 12.0
1413                        }
1414                    }
1415                    view {
1416                        style: {
1417                            flex_grow: 1.0
1418                            height: Length::Percent(100.0)
1419                            gradient: LinearGradient::new(
1420                                135.0,
1421                                Color::rgb(168, 85, 247),
1422                                Color::rgb(236, 72, 153),
1423                            )
1424                            radius: 12.0
1425                        }
1426                    }
1427                    image {
1428                        source: img_opaque
1429                        style: {
1430                            width: Length::Px(96.0)
1431                            height: Length::Px(96.0)
1432                        }
1433                    }
1434                    image {
1435                        source: img_rounded
1436                        style: {
1437                            width: Length::Px(132.0)
1438                            height: Length::Px(96.0)
1439                            radius: 14.0
1440                        }
1441                    }
1442                }
1443                canvas {
1444                    style: {
1445                        width: Length::Percent(100.0)
1446                        flex_grow: 1.0
1447                    }
1448                    painter: painter
1449                }
1450            }
1451        }
1452    });
1453    let wid: WindowId = app.get_window_state().get_id();
1454    let _: Result<FrameStats, PlatformError> = app.step_frame();
1455    let start: Instant = Instant::now();
1456    let mut last_hash: u64 = 0;
1457    let mut last_shaded: usize = 0;
1458    for _ in 0..count {
1459        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
1460        if let Ok(stats) = app.step_frame() {
1461            last_hash = stats.get_frame_hash();
1462            last_shaded = stats.get_pixels_shaded();
1463        }
1464    }
1465    build_metric(
1466        BENCH_SW_PRIMITIVES_NAME,
1467        count,
1468        start.elapsed(),
1469        format!("shaded={last_shaded} hash={last_hash:#018x}"),
1470    )
1471}
1472
1473/// Benchmarks 720x1280@2x software `EuvDrawer` portal slide-in and slide-out animation over 8 shadowed cards.
1474///
1475/// # Arguments
1476///
1477/// - `usize` - Number of 120Hz animated overlay frames to measure.
1478///
1479/// # Returns
1480///
1481/// - `BenchMetric` - Measured portal animation frame latency and throughput.
1482#[must_use]
1483pub fn bench_software_portal_overlay_anim(iterations: usize) -> BenchMetric {
1484    reset_reactive_runtime();
1485    let count: usize = iterations.max(1);
1486    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1487    let p: ThemePalette = tokens.get_palette();
1488    let mut win: WindowConfig = WindowConfig::default();
1489    win.set_size(360, 640).set_render(RenderConfig::software());
1490    let mut cfg: AppConfig = AppConfig::default();
1491    cfg.set_window(win);
1492    let Ok(mut app) = App::headless(cfg) else {
1493        return build_metric(
1494            BENCH_SW_PORTAL_ANIM_NAME,
1495            count,
1496            Duration::ZERO,
1497            String::new(),
1498        );
1499    };
1500    let drawer_open: Signal<bool> = Signal::new(false);
1501    let _: NodeId = app.mount(move || {
1502        let drawer_body: NodeId = view! {
1503            column {
1504                style: {
1505                    width: Length::Percent(100.0)
1506                    gap: SPACE_SM
1507                }
1508                text {
1509                    style: {
1510                        width: Length::Percent(100.0)
1511                        font_size: 13.0
1512                        color: p.get_muted_foreground()
1513                    }
1514                    { BENCH_DRAWER_BODY }
1515                }
1516                EuvBadge {
1517                    label: BENCH_BADGE.to_string()
1518                    tone: EuvTone::Primary
1519                    tokens: tokens
1520                }
1521                EuvProgress {
1522                    value: 0.68
1523                    tokens: tokens
1524                }
1525            }
1526        };
1527        view! {
1528            column {
1529                style: {
1530                    width: Length::Percent(100.0)
1531                    height: Length::Percent(100.0)
1532                    padding: Edges::all(SPACE_SM)
1533                    gap: SPACE_SM
1534                    background: p.get_background()
1535                }
1536                grid {
1537                    style: {
1538                        columns: 2
1539                        width: Length::Percent(100.0)
1540                        gap: SPACE_SM
1541                    }
1542                    for idx in 0..8usize {
1543                        EuvCard {
1544                            title: format!("{BENCH_TITLE} #{idx}")
1545                            tokens: tokens
1546                            subtitle: BENCH_CARD_CAPTION
1547                            EuvBadge {
1548                                label: BENCH_BADGE.to_string()
1549                                tone: EuvTone::Primary
1550                                tokens: tokens
1551                            }
1552                            EuvProgress {
1553                                value: ((idx % 7) as f32 + 1.0) * 0.12
1554                                tokens: tokens
1555                            }
1556                        }
1557                    }
1558                }
1559                EuvDrawer {
1560                    open: drawer_open
1561                    title: BENCH_DRAWER_TITLE.to_string()
1562                    body: drawer_body
1563                    tokens: tokens
1564                }
1565            }
1566        }
1567    });
1568    app.set_exact_physical_viewport(720, 1280, 2.0);
1569    let _: Result<FrameStats, PlatformError> = app.step_frame();
1570    let toggle_step: usize = (count / 2).max(1);
1571    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
1572    let start: Instant = Instant::now();
1573    let mut last_hash: u64 = 0;
1574    let mut last_shaded: usize = 0;
1575    let _: bool = drawer_open.set_if_changed(true);
1576    for step in 0..count {
1577        if step == toggle_step && count > 1 {
1578            let _: bool = drawer_open.set_if_changed(false);
1579        }
1580        if let Ok(stats) = app.step_game_frame(1.0 / 120.0) {
1581            last_hash = stats.get_frame_hash();
1582            last_shaded = stats.get_pixels_shaded();
1583        }
1584    }
1585    let elapsed: Duration = start.elapsed();
1586    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
1587    drop(alloc_guard);
1588    let denom: f64 = count as f64;
1589    build_metric(
1590        BENCH_SW_PORTAL_ANIM_NAME,
1591        count,
1592        elapsed,
1593        format!(
1594            "res=720x1280@2x shaded={last_shaded} allocs={:.1}/f bytes={:.0}B/f hash={last_hash:#018x}",
1595            (alloc_snap.get_alloc_count() as f64) / denom,
1596            (alloc_snap.get_bytes_allocated() as f64) / denom,
1597        ),
1598    )
1599    .with_allocations(alloc_snap)
1600}
1601
1602/// Benchmarks active per-frame dirty mutation through `PaintPass::build` and `HardwareRenderer::render` on every iteration.
1603///
1604/// # Arguments
1605///
1606/// - `usize` - Number of actively mutated hardware frames to measure.
1607///
1608/// # Returns
1609///
1610/// - `BenchMetric` - Measured active hardware batching latency and total draw batches.
1611#[must_use]
1612pub fn bench_hardware_active_batching(iterations: usize) -> BenchMetric {
1613    reset_reactive_runtime();
1614    let count: usize = iterations.max(1);
1615    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1616    let p: ThemePalette = tokens.get_palette();
1617    let mut win: WindowConfig = WindowConfig::default();
1618    win.set_size(800, 600).set_render(RenderConfig::hardware());
1619    let mut cfg: AppConfig = AppConfig::default();
1620    cfg.set_window(win);
1621    let Ok(mut app) = App::headless(cfg) else {
1622        return build_metric(
1623            BENCH_HW_ACTIVE_BATCH_NAME,
1624            count,
1625            Duration::ZERO,
1626            String::new(),
1627        );
1628    };
1629    let mut accent_node: NodeId = NodeId::default();
1630    let _: NodeId = app.mount(|| {
1631        view! {
1632            column {
1633                style: {
1634                    width: Length::Percent(100.0)
1635                    height: Length::Percent(100.0)
1636                    padding: Edges::all(SPACE_MD)
1637                    gap: SPACE_SM
1638                    background: p.get_background()
1639                }
1640                EuvHeader {
1641                    title: BENCH_TITLE.to_string()
1642                    subtitle: BENCH_SUBTITLE.to_string()
1643                    tokens: tokens
1644                }
1645                view {
1646                    node_ref: accent_node
1647                    style: {
1648                        width: Length::Percent(100.0)
1649                        height: Length::Px(12.0)
1650                        radius: 6.0
1651                        background: p.get_primary()
1652                    }
1653                }
1654                grid {
1655                    style: {
1656                        columns: 2
1657                        width: Length::Percent(100.0)
1658                        gap: SPACE_SM
1659                    }
1660                    for idx in 0..8usize {
1661                        EuvCard {
1662                            title: format!("{BENCH_TITLE} #{idx}")
1663                            tokens: tokens
1664                            subtitle: BENCH_SUBTITLE
1665                            EuvBadge {
1666                                label: BENCH_BADGE.to_string()
1667                                tone: EuvTone::Primary
1668                                tokens: tokens
1669                            }
1670                            EuvProgress {
1671                                value: ((idx % 7) as f32 + 1.0) * 0.12
1672                                tokens: tokens
1673                            }
1674                        }
1675                    }
1676                }
1677            }
1678        }
1679    });
1680    let _: Result<FrameStats, PlatformError> = app.step_frame();
1681    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
1682    let start: Instant = Instant::now();
1683    let mut last_batches: usize = 0;
1684    let mut total_batches: usize = 0;
1685    for step in 0..count {
1686        let next_opacity: f32 = if step % 2 == 0 { 0.85 } else { 1.0 };
1687        app.get_scene().with_write(
1688            |tree: &mut SceneTree| {
1689                if let Some(node) = tree.get_node(accent_node) {
1690                    let mut st: Style = *node.style_ref();
1691                    st.get_mut_paint().set_opacity(next_opacity);
1692                    tree.set_style(accent_node, st);
1693                }
1694            },
1695            (),
1696        );
1697        if let Ok(stats) = app.step_frame() {
1698            last_batches = stats.get_draw_batches();
1699            total_batches += last_batches;
1700        }
1701    }
1702    let elapsed: Duration = start.elapsed();
1703    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
1704    drop(alloc_guard);
1705    let denom: f64 = count as f64;
1706    build_metric(
1707        BENCH_HW_ACTIVE_BATCH_NAME,
1708        count,
1709        elapsed,
1710        format!(
1711            "batches={last_batches} total_batches={total_batches} allocs={:.1}/f bytes={:.0}B/f",
1712            (alloc_snap.get_alloc_count() as f64) / denom,
1713            (alloc_snap.get_bytes_allocated() as f64) / denom,
1714        ),
1715    )
1716    .with_allocations(alloc_snap)
1717}
1718
1719/// Benchmarks `DeterministicTextMeasurer::measure` and `measure_size` on mixed ASCII/CJK paragraphs alongside hot `GlyphAtlas` hits.
1720///
1721/// # Arguments
1722///
1723/// - `usize` - Number of text measurement and glyph lookup iterations to measure.
1724///
1725/// # Returns
1726///
1727/// - `BenchMetric` - Measured latency, throughput, and checksum.
1728#[must_use]
1729pub fn bench_font_text_wrap_measure_cache(iterations: usize) -> BenchMetric {
1730    let count: usize = iterations.max(1);
1731    let measurer: DeterministicTextMeasurer = DeterministicTextMeasurer;
1732    let style: TextStyle = TextStyle::default();
1733    let mut atlas: GlyphAtlas = GlyphAtlas::default();
1734    let hot_chars: [char; 12] = [
1735        'E', 'u', 'v', 'R', 's', 't', '0', '9', '跨', '端', '原', '生',
1736    ];
1737    let keys: Vec<GlyphKey> = hot_chars
1738        .iter()
1739        .map(|ch: &char| GlyphKey::new(*ch, 140, false))
1740        .collect();
1741    for key in keys.iter().copied() {
1742        let _: &RasterizedGlyph = atlas.get_or_rasterize(key);
1743    }
1744    let start: Instant = Instant::now();
1745    let mut checksum: f32 = 0.0;
1746    for _ in 0..count {
1747        let wrapped: TextLayoutResult = measurer.measure(BENCH_PARA_MIXED_A, style, Some(280.0));
1748        let sz_wrapped: Size = measurer.measure_size(BENCH_PARA_MIXED_B, style, Some(280.0));
1749        let sz_single: Size = measurer.measure_size(BENCH_PARA_SINGLE, style, None);
1750        checksum +=
1751            wrapped.get_size().get_height() + sz_wrapped.get_width() + sz_single.get_width();
1752        for key in keys.iter().copied() {
1753            let glyph: &RasterizedGlyph = atlas.get_or_rasterize(key);
1754            checksum += glyph.get_advance() as f32;
1755        }
1756    }
1757    build_metric(
1758        BENCH_FONT_WRAP_CACHE_NAME,
1759        count,
1760        start.elapsed(),
1761        format!("atlas_glyphs={} checksum={checksum:.0}", atlas.len()),
1762    )
1763}
1764
1765/// Benchmarks fractional `+3.7px` wheel scrolling and active pointer hover moves at 240Hz across a 1,000-row scroll viewport.
1766///
1767/// # Arguments
1768///
1769/// - `usize` - Number of 240Hz fractional scroll ticks to measure.
1770///
1771/// # Returns
1772///
1773/// - `BenchMetric` - Measured smooth-scroll latency and throughput.
1774#[must_use]
1775pub fn bench_app_smooth_scroll_fractional(iterations: usize) -> BenchMetric {
1776    reset_reactive_runtime();
1777    let count: usize = iterations.max(1);
1778    let mut win: WindowConfig = WindowConfig::default();
1779    win.set_size(360, 792).set_render(RenderConfig::hardware());
1780    let mut cfg: AppConfig = AppConfig::default();
1781    cfg.set_window(win);
1782    let Ok(mut app) = App::headless(cfg) else {
1783        return build_metric(
1784            BENCH_APP_SMOOTH_SCROLL_NAME,
1785            count,
1786            Duration::ZERO,
1787            String::new(),
1788        );
1789    };
1790    let _: NodeId = app.mount(|| {
1791        view! {
1792            scroll {
1793                style: {
1794                    width: Length::Percent(100.0)
1795                    height: Length::Percent(100.0)
1796                    gap: 4.0
1797                }
1798                for idx in 0..1_000usize {
1799                    row {
1800                        style: {
1801                            width: Length::Percent(100.0)
1802                            height: Length::Px(32.0)
1803                            cursor: CursorIcon::Pointer
1804                        }
1805                        text {
1806                            { format!("{BENCH_ROW_LABEL} #{idx}") }
1807                        }
1808                    }
1809                }
1810            }
1811        }
1812    });
1813    let wid: WindowId = app.get_window_state().get_id();
1814    let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 120.0);
1815    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
1816    let start: Instant = Instant::now();
1817    let mut total_layout_nodes: usize = 0;
1818    let mut total_batches: usize = 0;
1819    for step in 0..count {
1820        let hover_y: f32 = 120.0 + ((step % 40) as f32) * 8.0;
1821        app.dispatch_window_event(WindowEvent::PointerMove(
1822            wid,
1823            PointerEvent::mouse(180.0, hover_y),
1824        ));
1825        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 3.7)));
1826        if let Ok(stats) = app.step_game_frame(1.0 / 240.0) {
1827            total_layout_nodes += stats.get_layout_nodes();
1828            total_batches += stats.get_draw_batches();
1829        }
1830    }
1831    let elapsed: Duration = start.elapsed();
1832    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
1833    drop(alloc_guard);
1834    let denom: f64 = count as f64;
1835    build_metric(
1836        BENCH_APP_SMOOTH_SCROLL_NAME,
1837        count,
1838        elapsed,
1839        format!(
1840            "rows=1000 layout_nodes={total_layout_nodes} batches={total_batches} allocs={:.1}/f bytes={:.0}B/f",
1841            (alloc_snap.get_alloc_count() as f64) / denom,
1842            (alloc_snap.get_bytes_allocated() as f64) / denom,
1843        ),
1844    )
1845    .with_allocations(alloc_snap)
1846}
1847
1848/// Benchmarks parsing, mounting, and disposing a full GFM `EuvMarkdown` document containing a 6x4 table, task list, alert, and 60-line Rust `EuvCodeBlock`.
1849///
1850/// # Arguments
1851///
1852/// - `usize` - Number of mount + dispose cycles to measure.
1853///
1854/// # Returns
1855///
1856/// - `BenchMetric` - Measured Markdown mount latency and scene node count.
1857#[must_use]
1858pub fn bench_ui_markdown_codeblock_mount(iterations: usize) -> BenchMetric {
1859    reset_reactive_runtime();
1860    let count: usize = iterations.max(1);
1861    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Dark);
1862    let scene: SceneHandle = SceneHandle::new_tree();
1863    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
1864    let start: Instant = Instant::now();
1865    let mut peak_nodes: usize = 0;
1866    for _ in 0..count {
1867        let (scope, root_node): (Scope, NodeId) = with_context(ctx.clone(), || {
1868            Scope::run(|_: Scope| {
1869                view! {
1870                    EuvMarkdown {
1871                        source: BENCH_MARKDOWN_DOC.to_string()
1872                        tokens: tokens
1873                    }
1874                }
1875            })
1876        });
1877        let live: usize = scene.with_read(|tree: &SceneTree| tree.live_node_count(), 0);
1878        peak_nodes = peak_nodes.max(live);
1879        scope.dispose();
1880        scene.with_write(|tree: &mut SceneTree| tree.dispose_subtree(root_node), ());
1881    }
1882    build_metric(
1883        BENCH_UI_MARKDOWN_MOUNT_NAME,
1884        count,
1885        start.elapsed(),
1886        format!(
1887            "peak_nodes={peak_nodes} doc_bytes={}",
1888            BENCH_MARKDOWN_DOC.len()
1889        ),
1890    )
1891}
1892
1893/// Benchmarks mounting and disposing a ~500-node declarative `view!` tree combining `style!` with `EuvCard`, `EuvButton`, `EuvBadge`, `EuvProgress`, `EuvTag`, and `EuvStatCard`.
1894///
1895/// # Arguments
1896///
1897/// - `usize` - Number of mount + dispose cycles to measure.
1898///
1899/// # Returns
1900///
1901/// - `BenchMetric` - Measured declarative mount latency and live node count per mount.
1902#[must_use]
1903pub fn bench_ui_view_macro_mount_500_nodes(iterations: usize) -> BenchMetric {
1904    reset_reactive_runtime();
1905    let count: usize = iterations.max(1);
1906    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1907    let p: ThemePalette = tokens.get_palette();
1908    let g: ThemeGeometry = tokens.get_geometry();
1909    let scene: SceneHandle = SceneHandle::new_tree();
1910    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
1911    let start: Instant = Instant::now();
1912    let mut nodes_per_mount: usize = 0;
1913    for _ in 0..count {
1914        let (scope, root_node): (Scope, NodeId) = with_context(ctx.clone(), || {
1915            Scope::run(|_: Scope| {
1916                let shell_style: Style = style! {
1917                    FlexDirection::Column
1918                    Overflow::Hidden
1919                    width: Length::Px(1200.0)
1920                    padding: Edges::all(SPACE_MD)
1921                    gap: SPACE_SM
1922                    background: p.get_background()
1923                };
1924                let strip_style: Style = style! {
1925                    FlexDirection::Row
1926                    AlignItems::Center
1927                    gap: SPACE_XS
1928                    width: Length::Percent(100.0)
1929                    border: (g.get_border_width(), p.get_border())
1930                    radius: g.get_radius_sm()
1931                    padding: Edges::all(SPACE_XS)
1932                };
1933                view! {
1934                    view {
1935                        style: shell_style
1936                        for idx in 0..27usize {
1937                            EuvCard {
1938                                title: format!("{BENCH_TITLE} #{idx}")
1939                                tokens: tokens
1940                                subtitle: BENCH_SUBTITLE
1941                                view {
1942                                    style: strip_style
1943                                    EuvButton {
1944                                        label: BENCH_BTN_LABEL.to_string()
1945                                        variant: EuvButtonVariant::Secondary
1946                                        size: EuvButtonSize::Small
1947                                        tokens: tokens
1948                                    }
1949                                    EuvBadge {
1950                                        label: BENCH_BADGE.to_string()
1951                                        tone: EuvTone::Primary
1952                                        tokens: tokens
1953                                    }
1954                                    EuvTag {
1955                                        label: BENCH_TAG_LABEL.to_string()
1956                                        tone: EuvTone::Neutral
1957                                        tokens: tokens
1958                                    }
1959                                }
1960                                EuvProgress {
1961                                    value: ((idx % 9) as f32 + 1.0) * 0.1
1962                                    tokens: tokens
1963                                }
1964                                EuvStatCard {
1965                                    label: BENCH_STAT_LABEL.to_string()
1966                                    value: format!("{}k", idx + 10)
1967                                    caption: BENCH_STAT_CAPTION.to_string()
1968                                    tokens: tokens
1969                                }
1970                            }
1971                        }
1972                    }
1973                }
1974            })
1975        });
1976        nodes_per_mount = scene.with_read(|tree: &SceneTree| tree.live_node_count(), 0);
1977        scope.dispose();
1978        scene.with_write(|tree: &mut SceneTree| tree.dispose_subtree(root_node), ());
1979    }
1980    build_metric(
1981        BENCH_UI_VIEW_MOUNT_500_NAME,
1982        count,
1983        start.elapsed(),
1984        format!("nodes_per_mount={nodes_per_mount}"),
1985    )
1986}
1987
1988/// Benchmarks cycling across 8 `PageRetention::Freeze` routes in `EuvRouter` + `EuvRouterOutlet` paired with `EuvSidebarNav` and `EuvTabs`.
1989///
1990/// # Arguments
1991///
1992/// - `usize` - Number of route switches and frame steps to measure.
1993///
1994/// # Returns
1995///
1996/// - `BenchMetric` - Measured route switch latency and frozen route count.
1997#[must_use]
1998pub fn bench_ui_router_freeze_switch(iterations: usize) -> BenchMetric {
1999    reset_reactive_runtime();
2000    let count: usize = iterations.max(1);
2001    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
2002    let mut win: WindowConfig = WindowConfig::default();
2003    win.set_size(800, 600).set_render(RenderConfig::hardware());
2004    let mut cfg: AppConfig = AppConfig::default();
2005    cfg.set_window(win);
2006    let Ok(mut app) = App::headless(cfg) else {
2007        return build_metric(
2008            BENCH_UI_ROUTER_FREEZE_NAME,
2009            count,
2010            Duration::ZERO,
2011            String::new(),
2012        );
2013    };
2014    let mut router: EuvRouter =
2015        EuvRouter::new(BENCH_ROUTE_PATHS[0]).with_default_retention(PageRetention::Freeze);
2016    for idx in 0..BENCH_ROUTE_PATHS.len() {
2017        let route_label: &'static str = BENCH_ROUTE_LABELS[idx];
2018        router = router.route(
2019            BENCH_ROUTE_PATHS[idx],
2020            route_label,
2021            move |_matched: &EuvRouteMatch| {
2022                let counter: Signal<u32> = Signal::new(idx as u32);
2023                let label_text: Box<dyn Fn() -> String> =
2024                    Box::new(move || format!("{route_label} active={}", counter.get()));
2025                view! {
2026                    EuvCard {
2027                        title: route_label.to_string()
2028                        tokens: tokens
2029                        subtitle: BENCH_SUBTITLE
2030                        text {
2031                            style: {
2032                                width: Length::Percent(100.0)
2033                                font_size: 13.0
2034                            }
2035                            { label_text }
2036                        }
2037                        EuvProgress {
2038                            value: ((idx as f32) + 1.0) * 0.11
2039                            tokens: tokens
2040                        }
2041                    }
2042                }
2043            },
2044        );
2045    }
2046    let active_tab: Signal<usize> = Signal::new(0);
2047    let router_mount: EuvRouter = router.clone();
2048    let _: NodeId = app.mount(move || {
2049        let nav_items: Vec<EuvNavItem> = BENCH_ROUTE_PATHS
2050            .iter()
2051            .zip(BENCH_ROUTE_LABELS.iter())
2052            .map(|(path, label): (&&str, &&str)| {
2053                EuvNavItem::new((*path).to_string(), (*label).to_string())
2054            })
2055            .collect();
2056        let tab_labels: Vec<String> = BENCH_ROUTE_LABELS
2057            .iter()
2058            .map(|label: &&str| (*label).to_string())
2059            .collect();
2060        let outlet: EuvRouterOutlet = router_mount.outlet(|_m: &EuvRouteMatch| {
2061            view! {
2062                text {
2063                    { BENCH_FALLBACK_LABEL }
2064                }
2065            }
2066        });
2067        let outlet_node: NodeId = outlet.mount();
2068        view! {
2069            row {
2070                style: {
2071                    width: Length::Percent(100.0)
2072                    height: Length::Percent(100.0)
2073                    padding: Edges::all(SPACE_SM)
2074                    gap: SPACE_MD
2075                }
2076                column {
2077                    style: {
2078                        width: Length::Px(180.0)
2079                    }
2080                    EuvSidebarNav {
2081                        items: nav_items
2082                        active_route: router_mount.get_current_path()
2083                        tokens: tokens
2084                    }
2085                }
2086                column {
2087                    style: {
2088                        flex_grow: 1.0
2089                        gap: SPACE_SM
2090                    }
2091                    EuvTabs {
2092                        labels: tab_labels
2093                        active: active_tab
2094                        tokens: tokens
2095                    }
2096                    { outlet_node }
2097                }
2098            }
2099        }
2100    });
2101    let _: Result<FrameStats, PlatformError> = app.step_frame();
2102    let start: Instant = Instant::now();
2103    for step in 0..count {
2104        let idx: usize = (step + 1) % BENCH_ROUTE_PATHS.len();
2105        router.push(BENCH_ROUTE_PATHS[idx]);
2106        let _: bool = active_tab.set_if_changed(idx);
2107        let _: Result<FrameStats, PlatformError> = app.step_frame();
2108    }
2109    build_metric(
2110        BENCH_UI_ROUTER_FREEZE_NAME,
2111        count,
2112        start.elapsed(),
2113        format!(
2114            "routes=8 frozen={} switches={count}",
2115            router.get_frozen_count().get_untracked()
2116        ),
2117    )
2118}
2119
2120/// Benchmarks filter query updates, sort-order toggles, and single-row selection changes on a 120-row by 5-column `EuvDataTable`.
2121///
2122/// # Arguments
2123///
2124/// - `usize` - Number of alternating table mutation + frame steps to measure.
2125///
2126/// # Returns
2127///
2128/// - `BenchMetric` - Measured data table update latency and throughput.
2129#[must_use]
2130pub fn bench_ui_datatable_filter_select(iterations: usize) -> BenchMetric {
2131    reset_reactive_runtime();
2132    let count: usize = iterations.max(1);
2133    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
2134    let mut win: WindowConfig = WindowConfig::default();
2135    win.set_size(800, 600).set_render(RenderConfig::hardware());
2136    let mut cfg: AppConfig = AppConfig::default();
2137    cfg.set_window(win);
2138    let Ok(mut app) = App::headless(cfg) else {
2139        return build_metric(
2140            BENCH_UI_DATATABLE_NAME,
2141            count,
2142            Duration::ZERO,
2143            String::new(),
2144        );
2145    };
2146    let headers: Vec<String> = BENCH_TABLE_HEADERS
2147        .iter()
2148        .map(|h: &&str| (*h).to_string())
2149        .collect();
2150    let mut rows: Vec<Vec<String>> = Vec::with_capacity(120);
2151    for idx in 0..120usize {
2152        let team: &'static str = BENCH_TABLE_TEAMS[idx % BENCH_TABLE_TEAMS.len()];
2153        let status: &'static str = BENCH_TABLE_STATUSES[idx % BENCH_TABLE_STATUSES.len()];
2154        rows.push(vec![
2155            format!("{idx:03}"),
2156            format!("{team}-{idx:03}"),
2157            team.to_string(),
2158            format!("{}.{}ms", 1 + (idx % 9), idx % 10),
2159            status.to_string(),
2160        ]);
2161    }
2162    let filter_sig: Signal<String> = Signal::new(String::new());
2163    let sort_sig: Signal<bool> = Signal::new(true);
2164    let selected_sig: Signal<Option<usize>> = Signal::new(None);
2165    let _: NodeId = app.mount(move || {
2166        view! {
2167            scroll {
2168                style: {
2169                    width: Length::Percent(100.0)
2170                    height: Length::Percent(100.0)
2171                    padding: Edges::all(SPACE_SM)
2172                }
2173                EuvDataTable {
2174                    headers: headers
2175                    rows: rows
2176                    filter: filter_sig
2177                    sort_ascending: sort_sig
2178                    selected_row: selected_sig
2179                    tokens: tokens
2180                }
2181            }
2182        }
2183    });
2184    let _: Result<FrameStats, PlatformError> = app.step_frame();
2185    let start: Instant = Instant::now();
2186    for step in 0..count {
2187        match step % 3 {
2188            0 => {
2189                let query: &'static str =
2190                    BENCH_TABLE_FILTERS[(step / 3) % BENCH_TABLE_FILTERS.len()];
2191                let _: bool = filter_sig.set_if_changed(query.to_string());
2192            }
2193            1 => {
2194                let next_sort: bool = !sort_sig.get_untracked();
2195                let _: bool = sort_sig.set_if_changed(next_sort);
2196            }
2197            _ => {
2198                let _: bool = selected_sig.set_if_changed(Some(step % 40));
2199            }
2200        }
2201        let _: Result<FrameStats, PlatformError> = app.step_frame();
2202    }
2203    build_metric(
2204        BENCH_UI_DATATABLE_NAME,
2205        count,
2206        start.elapsed(),
2207        format!("rows=120 cols=5 updates={count}"),
2208    )
2209}
2210
2211/// Runs the complete reproducible benchmark and stress-test suite across reactivity, layout, virtual lists, WASM OTA, high-DPI rendering, input, UI, and game physics.
2212///
2213/// # Returns
2214///
2215/// - `BenchReport` - Aggregated benchmark results.
2216#[must_use]
2217pub fn run_full_benchmark_suite() -> BenchReport {
2218    run_filtered_benchmark_suite(None)
2219}
2220
2221/// Runs the benchmark suite optionally restricted to metrics whose canonical name contains `filter`.
2222///
2223/// # Arguments
2224///
2225/// - `Option<&str>` - Optional case-sensitive substring filter; `None` executes all 28 benchmarks.
2226///
2227/// # Returns
2228///
2229/// - `BenchReport` - Aggregated results for all matching benchmarks.
2230#[must_use]
2231pub fn run_filtered_benchmark_suite(filter: Option<&str>) -> BenchReport {
2232    let entries: [BenchCase; 28] = [
2233        BenchCase {
2234            name: BENCH_REACTIVE_NAME,
2235            runner: || bench_reactive_signals_and_memos(10_000),
2236        },
2237        BenchCase {
2238            name: BENCH_SELECTOR_NAME,
2239            runner: || bench_selector_o1(10_000),
2240        },
2241        BenchCase {
2242            name: BENCH_LAYOUT_CACHE_NAME,
2243            runner: || bench_layout_cache(1_000),
2244        },
2245        BenchCase {
2246            name: BENCH_GLYPH_ATLAS_NAME,
2247            runner: || bench_unicode_glyph_atlas(100),
2248        },
2249        BenchCase {
2250            name: BENCH_SW_FULL_NAME,
2251            runner: || bench_software_full_redraw(20),
2252        },
2253        BenchCase {
2254            name: BENCH_SW_RASTER_NAME,
2255            runner: || bench_software_rasterizer(20),
2256        },
2257        BenchCase {
2258            name: BENCH_HW_BATCH_NAME,
2259            runner: || bench_hardware_gpu_batching(200),
2260        },
2261        BenchCase {
2262            name: BENCH_GAME_PHYSICS_NAME,
2263            runner: || bench_game_ecs_physics(200),
2264        },
2265        BenchCase {
2266            name: BENCH_GAME_PARTICLES_NAME,
2267            runner: || bench_game_particles(1_000),
2268        },
2269        BenchCase {
2270            name: BENCH_GAME_3D_RT_NAME,
2271            runner: || bench_game3d_pbr_bvh_raytrace(BENCH_GAME3D_DEFAULT_ITERS),
2272        },
2273        BenchCase {
2274            name: BENCH_GAME_3D_MAX_RT_NAME,
2275            runner: || bench_game3d_cinematic_max_rt(BENCH_GAME3D_DEFAULT_ITERS),
2276        },
2277        BenchCase {
2278            name: BENCH_STRESS_LONG_LIST_NAME,
2279            runner: || bench_stress_long_list_100k(30),
2280        },
2281        BenchCase {
2282            name: BENCH_STRESS_COMPLEX_LAYOUT_NAME,
2283            runner: || bench_stress_complex_layout_2000(40),
2284        },
2285        BenchCase {
2286            name: BENCH_STRESS_BULK_REACTIVE_NAME,
2287            runner: || bench_stress_bulk_reactive_1000(20),
2288        },
2289        BenchCase {
2290            name: BENCH_STRESS_WASM_LOAD_NAME,
2291            runner: || bench_stress_wasm_dynamic_hotswap(30),
2292        },
2293        BenchCase {
2294            name: BENCH_STRESS_HIDPI_4X_NAME,
2295            runner: || bench_stress_hidpi_4x_1440x3168(15),
2296        },
2297        BenchCase {
2298            name: BENCH_STRESS_INPUT_HITTEST_NAME,
2299            runner: || bench_stress_scroll_physics_and_hittest(240),
2300        },
2301        BenchCase {
2302            name: BENCH_SW_ROUNDED_CLIP_NAME,
2303            runner: || bench_software_rounded_clip_cards(20),
2304        },
2305        BenchCase {
2306            name: BENCH_SW_PRIMITIVES_NAME,
2307            runner: || bench_software_primitives_image_vec(25),
2308        },
2309        BenchCase {
2310            name: BENCH_SW_PORTAL_ANIM_NAME,
2311            runner: || bench_software_portal_overlay_anim(30),
2312        },
2313        BenchCase {
2314            name: BENCH_HW_ACTIVE_BATCH_NAME,
2315            runner: || bench_hardware_active_batching(200),
2316        },
2317        BenchCase {
2318            name: BENCH_FONT_WRAP_CACHE_NAME,
2319            runner: || bench_font_text_wrap_measure_cache(2_000),
2320        },
2321        BenchCase {
2322            name: BENCH_APP_SMOOTH_SCROLL_NAME,
2323            runner: || bench_app_smooth_scroll_fractional(240),
2324        },
2325        BenchCase {
2326            name: BENCH_UI_MARKDOWN_MOUNT_NAME,
2327            runner: || bench_ui_markdown_codeblock_mount(40),
2328        },
2329        BenchCase {
2330            name: BENCH_UI_VIEW_MOUNT_500_NAME,
2331            runner: || bench_ui_view_macro_mount_500_nodes(50),
2332        },
2333        BenchCase {
2334            name: BENCH_UI_ROUTER_FREEZE_NAME,
2335            runner: || bench_ui_router_freeze_switch(100),
2336        },
2337        BenchCase {
2338            name: BENCH_UI_DATATABLE_NAME,
2339            runner: || bench_ui_datatable_filter_select(100),
2340        },
2341        BenchCase {
2342            name: TTFF_BENCH_NAME,
2343            runner: || bench_cold_start_ttff(TTFF_DEFAULT_ITERS),
2344        },
2345    ];
2346    let mut metrics: Vec<BenchMetric> = Vec::with_capacity(entries.len());
2347    for entry in entries.iter() {
2348        let selected: bool = filter
2349            .map(|substr: &str| entry.name.contains(substr))
2350            .unwrap_or(true);
2351        if selected {
2352            metrics.push((entry.runner)());
2353        }
2354    }
2355    BenchReport::new(metrics)
2356}
2357
2358/// Builds a deterministic RGBA8 test image buffer for image and sprite-sheet raster benchmarks.
2359///
2360/// # Arguments
2361///
2362/// - `u32` - Width in pixels.
2363/// - `u32` - Height in pixels.
2364/// - `u8` - Constant alpha channel value.
2365///
2366/// # Returns
2367///
2368/// - `ImageBuffer` - Populated deterministic RGBA8 pixel buffer.
2369fn build_test_image_buffer(width: u32, height: u32, alpha: u8) -> ImageBuffer {
2370    let pixel_count: usize = (width as usize).saturating_mul(height as usize);
2371    let mut pixels: Vec<u8> = Vec::with_capacity(pixel_count.saturating_mul(4));
2372    for y in 0..height {
2373        for x in 0..width {
2374            pixels.push(((x.wrapping_mul(3) + y) & 0xFF) as u8);
2375            pixels.push(((y.wrapping_mul(3) + x) & 0xFF) as u8);
2376            pixels.push(((x ^ y).wrapping_mul(5) & 0xFF) as u8);
2377            pixels.push(alpha);
2378        }
2379    }
2380    ImageBuffer::new(width, height, pixels)
2381}
2382
2383/// Formats a `BenchReport` into an aligned terminal summary table.
2384///
2385/// # Arguments
2386///
2387/// - `&BenchReport` - Completed benchmark report.
2388///
2389/// # Returns
2390///
2391/// - `String` - Human-readable report table.
2392#[must_use]
2393pub fn format_bench_report(report: &BenchReport) -> String {
2394    let mut out: String = String::from(REPORT_HEADER);
2395    for m in report.get_metrics().iter() {
2396        out.push_str(&format!(
2397            "{:32} iters={:6} avg={:10.1} ns/op  throughput={:10.0} ops/s  allocs={:6.1}/op ({:8.0}B/op)  {}\n",
2398            m.get_name(),
2399            m.get_iterations(),
2400            m.get_ns_per_op(),
2401            m.get_ops_per_sec(),
2402            m.get_allocs_per_op(),
2403            m.get_bytes_per_op(),
2404            m.get_detail()
2405        ));
2406    }
2407    out
2408}
2409
2410/// Serializes a `BenchReport` to formatted JSON.
2411///
2412/// # Arguments
2413///
2414/// - `&BenchReport` - Completed benchmark report.
2415///
2416/// # Returns
2417///
2418/// - `String` - Pretty-printed JSON string.
2419#[must_use]
2420pub fn report_to_json(report: &BenchReport) -> String {
2421    to_string_pretty(report).unwrap_or_default()
2422}
2423
2424/// Shared rendering benchmark harness executing real filled, stroked, shadowed, and text batches on every measured frame.
2425///
2426/// # Arguments
2427///
2428/// - `&str` - Benchmark name.
2429/// - `RenderConfig` - Renderer pipeline configuration.
2430/// - `usize` - Number of active frames to measure.
2431///
2432/// # Returns
2433///
2434/// - `BenchMetric` - Measured frame telemetry guaranteed to execute non-zero draw batches.
2435fn bench_render_pipeline(name: &str, render: RenderConfig, iterations: usize) -> BenchMetric {
2436    reset_reactive_runtime();
2437    let count: usize = iterations.max(1);
2438    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
2439    let p: ThemePalette = tokens.get_palette();
2440    let g: ThemeGeometry = tokens.get_geometry();
2441    let mut win: WindowConfig = WindowConfig::default();
2442    win.set_size(800, 600).set_render(render);
2443    let mut cfg: AppConfig = AppConfig::default();
2444    cfg.set_window(win);
2445    let Ok(mut app) = App::headless(cfg) else {
2446        return build_metric(name, count, Duration::ZERO, String::new());
2447    };
2448    let mut accent_node: NodeId = NodeId::default();
2449    let _: NodeId = app.mount(|| {
2450        view! {
2451            column {
2452                style: {
2453                    width: Length::Percent(100.0)
2454                    height: Length::Percent(100.0)
2455                    padding: Edges::all(SPACE_MD)
2456                    gap: SPACE_SM
2457                    overflow: Overflow::Hidden
2458                    background: p.get_background()
2459                }
2460                EuvHeader {
2461                    title: BENCH_TITLE.to_string()
2462                    subtitle: BENCH_SUBTITLE.to_string()
2463                    tokens: tokens
2464                }
2465                view {
2466                    node_ref: accent_node
2467                    style: {
2468                        width: Length::Percent(100.0)
2469                        height: Length::Px(10.0)
2470                        radius: 5.0
2471                        background: p.get_primary()
2472                        border: (g.get_border_width(), p.get_border())
2473                    }
2474                }
2475                grid {
2476                    style: {
2477                        columns: 2
2478                        width: Length::Percent(100.0)
2479                        gap: SPACE_SM
2480                    }
2481                    for idx in 0..4usize {
2482                        column {
2483                            style: {
2484                                width: Length::Percent(100.0)
2485                                padding: Edges::all(SPACE_SM)
2486                                gap: SPACE_XS
2487                                overflow: Overflow::Hidden
2488                                background: p.get_card()
2489                                border: (g.get_border_width(), p.get_border())
2490                                radius: g.get_radius_md()
2491                                shadow: g.get_shadow_md()
2492                            }
2493                            text {
2494                                style: {
2495                                    width: Length::Percent(100.0)
2496                                    font_size: 13.0
2497                                    font_weight: FontWeight::SemiBold
2498                                    color: p.get_card_foreground()
2499                                }
2500                                { format!("{BENCH_TITLE} #{idx}") }
2501                            }
2502                            text {
2503                                style: {
2504                                    width: Length::Percent(100.0)
2505                                    font_size: 11.0
2506                                    color: p.get_muted_foreground()
2507                                }
2508                                { BENCH_CARD_WRAP_COPY }
2509                            }
2510                            EuvBadge {
2511                                label: BENCH_BADGE.to_string()
2512                                tone: EuvTone::Primary
2513                                tokens: tokens
2514                            }
2515                            EuvProgress {
2516                                value: 0.72
2517                                tokens: tokens
2518                            }
2519                        }
2520                    }
2521                }
2522            }
2523        }
2524    });
2525    let wid: WindowId = app.get_window_state().get_id();
2526    for _ in 0..BENCH_RENDER_WARMUP_FRAMES {
2527        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
2528        let _: Result<FrameStats, PlatformError> = app.step_frame();
2529    }
2530    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
2531    let start: Instant = Instant::now();
2532    let mut last_hash: u64 = 0;
2533    let mut last_batches: usize = 0;
2534    let mut min_batches: usize = usize::MAX;
2535    let mut total_batches: usize = 0;
2536    for step in 0..count {
2537        let next_opacity: f32 = if step % 2 == 0 { 0.85 } else { 1.0 };
2538        app.get_scene().with_write(
2539            |tree: &mut SceneTree| {
2540                let _: bool = tree.mutate_style(accent_node, |st: &mut Style| {
2541                    let _: &mut PaintStyle = st.get_mut_paint().set_opacity(next_opacity);
2542                });
2543            },
2544            (),
2545        );
2546        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
2547        if let Ok(stats) = app.step_frame() {
2548            last_hash = stats.get_frame_hash();
2549            last_batches = stats.get_draw_batches();
2550            min_batches = min_batches.min(last_batches);
2551            total_batches = total_batches.saturating_add(last_batches);
2552        }
2553    }
2554    let elapsed: Duration = start.elapsed();
2555    let alloc_snap: AllocationSnapshot = alloc_guard.elapsed_snapshot();
2556    drop(alloc_guard);
2557    if min_batches == usize::MAX {
2558        min_batches = 0;
2559    }
2560    assert!(
2561        last_batches > 0 && min_batches > 0,
2562        "render benchmark {name} must execute non-zero draw batches (last={last_batches}, min={min_batches})"
2563    );
2564    let denom: f64 = count as f64;
2565    build_metric(
2566        name,
2567        count,
2568        elapsed,
2569        format!(
2570            "batches={last_batches} min_batches={min_batches} total_batches={total_batches} allocs={:.1}/f bytes={:.0}B/f hash={last_hash:#018x}",
2571            (alloc_snap.get_alloc_count() as f64) / denom,
2572            (alloc_snap.get_bytes_allocated() as f64) / denom,
2573        ),
2574    )
2575    .with_allocations(alloc_snap)
2576}
2577
2578/// Constructs a `BenchMetric` from elapsed wall time and iteration count.
2579///
2580/// # Arguments
2581///
2582/// - `&str` - Metric name.
2583/// - `usize` - Completed iterations.
2584/// - `Duration` - Total elapsed time.
2585/// - `String` - Extra metadata string.
2586///
2587/// # Returns
2588///
2589/// - `BenchMetric` - Computed timing metric.
2590fn build_metric(name: &str, iterations: usize, elapsed: Duration, detail: String) -> BenchMetric {
2591    BenchMetric::from_elapsed(name, iterations, elapsed, detail)
2592}