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                width: Length::Px(800.0)
85                height: Length::Px(600.0)
86                gap: SPACE_XS
87                for idx in 0..120usize {
88                    row {
89                        width: Length::Percent(100.0)
90                        height: Length::Px(24.0)
91                        text {
92                            { format!("{BENCH_ROW_LABEL} {idx}") }
93                        }
94                    }
95                }
96            }
97        }
98    });
99    scene.with_write(
100        |tree: &mut SceneTree| {
101            let root: NodeId = tree.get_root();
102            tree.replace_children(root, vec![container]);
103        },
104        (),
105    );
106    let mut engine: LayoutEngine = LayoutEngine::default();
107    let viewport: Size = Size::new(800.0, 600.0);
108    let _: LayoutStats = scene.with_write(
109        |tree: &mut SceneTree| engine.compute(tree, viewport),
110        LayoutStats::default(),
111    );
112    let start: Instant = Instant::now();
113    let mut cache_hits: usize = 0;
114    for _ in 0..count {
115        let stats: LayoutStats = scene.with_write(
116            |tree: &mut SceneTree| engine.compute(tree, viewport),
117            LayoutStats::default(),
118        );
119        cache_hits += stats.get_subtrees_skipped();
120    }
121    build_metric(
122        BENCH_LAYOUT_CACHE_NAME,
123        count,
124        start.elapsed(),
125        format!("cache_hits={cache_hits}"),
126    )
127}
128
129/// Benchmarks full 800x600 software SDF tile rasterization frames.
130///
131/// # Arguments
132///
133/// - `usize` - Number of rendered frames to measure.
134///
135/// # Returns
136///
137/// - `BenchMetric` - Measured frame latency, FPS throughput, and pixel hash.
138#[must_use]
139pub fn bench_software_rasterizer(iterations: usize) -> BenchMetric {
140    bench_render_pipeline(BENCH_SW_RASTER_NAME, RenderConfig::software(), iterations)
141}
142
143/// Benchmarks hardware GPU instanced draw-batch compilation frames.
144///
145/// # Arguments
146///
147/// - `usize` - Number of GPU frame submissions to measure.
148///
149/// # Returns
150///
151/// - `BenchMetric` - Measured frame latency, FPS throughput, and batch count.
152#[must_use]
153pub fn bench_hardware_gpu_batching(iterations: usize) -> BenchMetric {
154    bench_render_pipeline(BENCH_HW_BATCH_NAME, RenderConfig::hardware(), iterations)
155}
156
157/// Benchmarks Unicode + CJK glyph rasterization and GPU RGBA8 atlas shelf-packing.
158///
159/// # Arguments
160///
161/// - `usize` - Number of glyph-pack iterations to measure.
162///
163/// # Returns
164///
165/// - `BenchMetric` - Measured latency and packed glyph count.
166#[must_use]
167pub fn bench_unicode_glyph_atlas(iterations: usize) -> BenchMetric {
168    let count: usize = iterations.max(1);
169    let sample_chars: [char; 8] = ['A', 'g', '9', '跨', '端', '原', '生', '框'];
170    let provider: NativeSystemFont = NativeSystemFont::deterministic();
171    let start: Instant = Instant::now();
172    let mut packed_regions: usize = 0;
173    for _ in 0..count {
174        let mut atlas: GlyphAtlas = GlyphAtlas::default();
175        for ch in sample_chars.iter() {
176            let key: GlyphKey = GlyphKey::new(*ch, 160, false);
177            let _: &RasterizedGlyph = atlas.get_or_rasterize_with(key, &provider);
178        }
179        let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
180        packed_regions = packed.get_regions().len();
181    }
182    build_metric(
183        BENCH_GLYPH_ATLAS_NAME,
184        count,
185        start.elapsed(),
186        format!("packed_glyphs={packed_regions}"),
187    )
188}
189
190/// Benchmarks full forced-redraw 800x600 software SDF tile rasterization frames.
191///
192/// # Arguments
193///
194/// - `usize` - Number of full raster frames to measure.
195///
196/// # Returns
197///
198/// - `BenchMetric` - Measured full-frame raster latency and FPS throughput.
199#[must_use]
200pub fn bench_software_full_redraw(iterations: usize) -> BenchMetric {
201    reset_reactive_runtime();
202    let count: usize = iterations.max(1);
203    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
204    let mut win: WindowConfig = WindowConfig::default();
205    win.set_size(800, 600).set_render(RenderConfig::software());
206    let mut cfg: AppConfig = AppConfig::default();
207    cfg.set_window(win);
208    let Ok(mut app) = App::headless(cfg) else {
209        return build_metric(BENCH_SW_FULL_NAME, count, Duration::ZERO, String::new());
210    };
211    let _: NodeId = app.mount(|| {
212        view! {
213            column {
214                width: Length::Percent(100.0)
215                padding: Edges::all(SPACE_LG)
216                gap: SPACE_MD
217                EuvHeader {
218                    title: BENCH_TITLE.to_string()
219                    subtitle: BENCH_SUBTITLE.to_string()
220                    tokens: tokens
221                }
222                EuvCard {
223                    title: BENCH_TITLE.to_string()
224                    tokens: tokens
225                    subtitle: BENCH_SUBTITLE
226                    EuvBadge {
227                        label: BENCH_BADGE.to_string()
228                        tone: EuvTone::Primary
229                        tokens: tokens
230                    }
231                    EuvProgress {
232                        value: 0.72
233                        tokens: tokens
234                    }
235                }
236            }
237        }
238    });
239    let wid: WindowId = app.get_window_state().get_id();
240    let start: Instant = Instant::now();
241    let mut last_hash: u64 = 0;
242    let mut last_batches: usize = 0;
243    for _ in 0..count {
244        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
245        if let Ok(stats) = app.step_frame() {
246            last_hash = stats.get_frame_hash();
247            last_batches = stats.get_draw_batches();
248        }
249    }
250    build_metric(
251        BENCH_SW_FULL_NAME,
252        count,
253        start.elapsed(),
254        format!("batches={last_batches} hash={last_hash:#018x}"),
255    )
256}
257
258/// Benchmarks 256 dynamic 2D rigid bodies stepping through spatial-hash broad-phase and narrow-phase collision resolution.
259///
260/// # Arguments
261///
262/// - `usize` - Number of fixed 60Hz physics ticks to measure.
263///
264/// # Returns
265///
266/// - `BenchMetric` - Measured physics tick latency and collision throughput.
267#[must_use]
268pub fn bench_game_ecs_physics(iterations: usize) -> BenchMetric {
269    let count: usize = iterations.max(1);
270    let mut world: GameWorld = GameWorld::with_capacity(256);
271    for idx in 0..256usize {
272        let col: f32 = (idx % 16) as f32;
273        let row: f32 = (idx / 16) as f32;
274        let eid: EntityId = world.spawn(
275            EntityTag::Enemy,
276            Point::new(40.0 + col * 52.0, 40.0 + row * 40.0),
277        );
278        if let Some(ent) = world.get_entity_mut(eid) {
279            ent.set_velocity(Velocity2D::new(
280                if idx % 2 == 0 { 110.0 } else { -95.0 },
281                if idx % 3 == 0 { 85.0 } else { -75.0 },
282                0.0,
283            ));
284            ent.set_body(Some(RigidBody2D::dynamic(1.0, 0.9, 0.02)));
285            ent.set_collider(Some(Collider2D::circle(
286                10.0,
287                COLLISION_LAYER_ENEMY,
288                COLLISION_LAYER_ALL,
289                false,
290            )));
291        }
292    }
293    let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
294    phys_cfg.set_arena_bounds(Some(Rect::new(0.0, 0.0, 960.0, 720.0)));
295    let mut physics: PhysicsWorld2D = PhysicsWorld2D::with_config(phys_cfg);
296    let start: Instant = Instant::now();
297    let mut total_collisions: usize = 0;
298    for _ in 0..count {
299        let evs: Vec<CollisionEvent> = physics.step(&mut world, 1.0 / 60.0);
300        total_collisions += evs.len();
301    }
302    build_metric(
303        BENCH_GAME_PHYSICS_NAME,
304        count,
305        start.elapsed(),
306        format!("entities=256 collisions={total_collisions}"),
307    )
308}
309
310/// Benchmarks updating 1,024 active zero-allocation pooled particles per frame.
311///
312/// # Arguments
313///
314/// - `usize` - Number of particle update steps to measure.
315///
316/// # Returns
317///
318/// - `BenchMetric` - Measured particle update latency and throughput.
319#[must_use]
320pub fn bench_game_particles(iterations: usize) -> BenchMetric {
321    let count: usize = iterations.max(1);
322    let mut system: ParticleSystem = ParticleSystem::with_capacity(1024);
323    let mut cfg: ParticleEmitterConfig = ParticleEmitterConfig::default();
324    cfg.set_min_life(10.0).set_max_life(20.0);
325    system.emit_burst(Point::new(400.0, 300.0), 1024, cfg);
326    let start: Instant = Instant::now();
327    let mut live: usize = 0;
328    for _ in 0..count {
329        live = system.update(1.0 / 60.0);
330    }
331    build_metric(
332        BENCH_GAME_PARTICLES_NAME,
333        count,
334        start.elapsed(),
335        format!("active_particles={live}"),
336    )
337}
338
339/// Benchmarks the AAA 3D open-world PBR + BVH ray-traced shadows and reflections pipeline.
340///
341/// # Arguments
342///
343/// - `usize` - Number of 3D ray-traced frames to measure.
344///
345/// # Returns
346///
347/// - `BenchMetric` - Measured 3D frame latency, triangle throughput, and BVH ray count.
348#[must_use]
349pub fn bench_game3d_pbr_bvh_raytrace(iterations: usize) -> BenchMetric {
350    let count: usize = iterations.max(1);
351    let mut world: World3D = World3D::create_open_world_city();
352    let mut renderer: Renderer3D = Renderer3D::default();
353    let cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::High);
354    let start: Instant = Instant::now();
355    let mut last_rays: usize = 0;
356    let mut last_tris: usize = 0;
357    for _ in 0..count {
358        let _: ImageBuffer = renderer.render_world(&mut world, 480, 270, &cfg);
359        let st: RenderStats3D = renderer.get_last_stats();
360        last_rays = st.get_rays_traced();
361        last_tris = st.get_triangles_drawn();
362    }
363    build_metric(
364        BENCH_GAME_3D_RT_NAME,
365        count,
366        start.elapsed(),
367        format!("tris={last_tris} rays={last_rays}"),
368    )
369}
370
371/// Benchmarks maxed-out `Cinematic` + `FullPathTracedGi` + `125%` scale 3D ray tracing at HD resolution.
372///
373/// # Arguments
374///
375/// - `usize` - Number of max-settings 3D frames to measure.
376///
377/// # Returns
378///
379/// - `BenchMetric` - Measured frame latency, FPS throughput, resolution, and ray count.
380#[must_use]
381pub fn bench_game3d_cinematic_max_rt(iterations: usize) -> BenchMetric {
382    let count: usize = iterations.max(1);
383    let mut world: World3D = World3D::create_open_world_city();
384    let mut renderer: Renderer3D = Renderer3D::default();
385    let mut cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::Cinematic);
386    cfg.set_ray_tracing(RayTracingMode::FullPathTracedGi)
387        .set_resolution_scale(1.25);
388    let start: Instant = Instant::now();
389    let mut last_rays: usize = 0;
390    let mut last_w: u32 = 0;
391    let mut last_h: u32 = 0;
392    for _ in 0..count {
393        let _: ImageBuffer = renderer.render_world(&mut world, 960, 480, &cfg);
394        let st: RenderStats3D = renderer.get_last_stats();
395        last_rays = st.get_rays_traced();
396        last_w = st.get_render_width();
397        last_h = st.get_render_height();
398    }
399    build_metric(
400        BENCH_GAME_3D_MAX_RT_NAME,
401        count,
402        start.elapsed(),
403        format!("res={last_w}x{last_h} rays={last_rays}"),
404    )
405}
406
407/// Stress-benchmarks continuous scrolling of a 100,000-row `EuvVirtualList` through full layout and software rasterization.
408///
409/// # Arguments
410///
411/// - `usize` - Number of scrolled frames to measure.
412///
413/// # Returns
414///
415/// - `BenchMetric` - Measured frame latency, throughput, and final virtual scroll offset.
416#[must_use]
417pub fn bench_stress_long_list_100k(iterations: usize) -> BenchMetric {
418    reset_reactive_runtime();
419    let count: usize = iterations.max(1);
420    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
421    let p: ThemePalette = tokens.get_palette();
422    let g: ThemeGeometry = tokens.get_geometry();
423    let mut win: WindowConfig = WindowConfig::default();
424    win.set_size(400, 720).set_render(RenderConfig::software());
425    let mut cfg: AppConfig = AppConfig::default();
426    cfg.set_window(win);
427    let Ok(mut app) = App::headless(cfg) else {
428        return build_metric(
429            BENCH_STRESS_LONG_LIST_NAME,
430            count,
431            Duration::ZERO,
432            String::new(),
433        );
434    };
435    let scroll_y: Signal<f32> = Signal::new(0.0);
436    let _: NodeId = app.mount(|| {
437        let vlist: EuvVirtualList =
438            EuvVirtualList::new(100_000, 36.0, scroll_y, tokens).viewport_height(680.0);
439        vlist.mount_with(move |idx: usize| {
440            view! {
441                row {
442                    width: Length::Percent(100.0)
443                    height: Length::Px(36.0)
444                    padding: Edges::symmetric(SPACE_XS, SPACE_MD)
445                    align: AlignItems::Center
446                    border: (g.get_border_width(), p.get_border())
447                    text {
448                        font_size: 13.0
449                        color: p.get_foreground()
450                        { format!("{BENCH_ROW_LABEL} #{idx}") }
451                    }
452                }
453            }
454        })
455    });
456    let _: Result<FrameStats, PlatformError> = app.step_frame();
457    let start: Instant = Instant::now();
458    let mut last_shaded: usize = 0;
459    for step in 1..=count {
460        let next_y: f32 = ((step as f32) * 144.0) % 3_500_000.0;
461        let _: bool = scroll_y.set_if_changed(next_y);
462        if let Ok(stats) = app.step_frame() {
463            last_shaded = stats.get_pixels_shaded();
464        }
465    }
466    build_metric(
467        BENCH_STRESS_LONG_LIST_NAME,
468        count,
469        start.elapsed(),
470        format!(
471            "rows=100000 scroll_y={:.0}px shaded={last_shaded}",
472            scroll_y.get_untracked()
473        ),
474    )
475}
476
477/// Stress-benchmarks a deeply nested 2,000-node Flex/Grid layout tree under repeated full and dirty-subtree layout passes.
478///
479/// # Arguments
480///
481/// - `usize` - Number of layout passes to measure.
482///
483/// # Returns
484///
485/// - `BenchMetric` - Measured per-pass layout latency and node count.
486#[must_use]
487pub fn bench_stress_complex_layout_2000(iterations: usize) -> BenchMetric {
488    reset_reactive_runtime();
489    let count: usize = iterations.max(1);
490    let scene: SceneHandle = SceneHandle::new_tree();
491    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
492    let (leaf_nodes, page): (Vec<NodeId>, NodeId) = with_context(ctx, || {
493        let mut leaves: Vec<NodeId> = Vec::with_capacity(50);
494        let mut sections: Vec<NodeId> = Vec::with_capacity(50);
495        for section_idx in 0..50usize {
496            let mut first_title: NodeId = NodeId::default();
497            let grid_node: NodeId = view! {
498                grid {
499                    columns: 4
500                    width: Length::Percent(100.0)
501                    gap: SPACE_SM
502                    for card_idx in 0..8usize {
503                        column {
504                            width: Length::Percent(100.0)
505                            padding: Edges::all(SPACE_SM)
506                            gap: SPACE_XS
507                            row {
508                                width: Length::Percent(100.0)
509                                justify: JustifyContent::SpaceBetween
510                                if card_idx == 0 {
511                                    text {
512                                        node_ref: first_title
513                                        font_size: 13.0
514                                        { format!("{BENCH_CELL_LABEL} {section_idx}-{card_idx}") }
515                                    }
516                                } else {
517                                    text {
518                                        font_size: 13.0
519                                        { format!("{BENCH_CELL_LABEL} {section_idx}-{card_idx}") }
520                                    }
521                                }
522                                text {
523                                    font_size: 11.0
524                                    { format!("{section_idx}") }
525                                }
526                            }
527                        }
528                    }
529                }
530            };
531            leaves.push(first_title);
532            sections.push(grid_node);
533        }
534        let p_node: NodeId = view! {
535            column {
536                width: Length::Px(1280.0)
537                padding: Edges::all(SPACE_MD)
538                gap: SPACE_SM
539                ..sections
540            }
541        };
542        (leaves, p_node)
543    });
544    scene.with_write(
545        |tree: &mut SceneTree| {
546            let root: NodeId = tree.get_root();
547            tree.replace_children(root, vec![page]);
548        },
549        (),
550    );
551    let mut engine: LayoutEngine = LayoutEngine::default();
552    let viewport: Size = Size::new(1280.0, 800.0);
553    let init_stats: LayoutStats = scene.with_write(
554        |tree: &mut SceneTree| engine.compute(tree, viewport),
555        LayoutStats::default(),
556    );
557    let start: Instant = Instant::now();
558    let mut total_computed: usize = 0;
559    let mut total_skipped: usize = 0;
560    for step in 0..count {
561        let target: NodeId = leaf_nodes[step % leaf_nodes.len()];
562        scene.with_write(
563            |tree: &mut SceneTree| {
564                tree.set_text(target, format!("{BENCH_CELL_LABEL} #{step}"));
565                let stats: LayoutStats = engine.compute(tree, viewport);
566                total_computed += stats.get_nodes_computed();
567                total_skipped += stats.get_subtrees_skipped();
568            },
569            (),
570        );
571    }
572    build_metric(
573        BENCH_STRESS_COMPLEX_LAYOUT_NAME,
574        count,
575        start.elapsed(),
576        format!(
577            "initial_nodes={} avg_computed={} avg_skipped={}",
578            init_stats.get_nodes_computed(),
579            total_computed / count,
580            total_skipped / count
581        ),
582    )
583}
584
585/// Stress-benchmarks bulk batched updates across 1,000 live reactive UI components with subscribed signals and memos.
586///
587/// # Arguments
588///
589/// - `usize` - Number of full 1,000-component batch update ticks to measure.
590///
591/// # Returns
592///
593/// - `BenchMetric` - Measured batch update + reactive flush + scene patch latency.
594#[must_use]
595pub fn bench_stress_bulk_reactive_1000(iterations: usize) -> BenchMetric {
596    reset_reactive_runtime();
597    let count: usize = iterations.max(1);
598    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
599    let p: ThemePalette = tokens.get_palette();
600    let mut win: WindowConfig = WindowConfig::default();
601    win.set_size(800, 600).set_render(RenderConfig::hardware());
602    let mut cfg: AppConfig = AppConfig::default();
603    cfg.set_window(win);
604    let Ok(mut app) = App::headless(cfg) else {
605        return build_metric(
606            BENCH_STRESS_BULK_REACTIVE_NAME,
607            count,
608            Duration::ZERO,
609            String::new(),
610        );
611    };
612    let mut signals: Vec<Signal<u32>> = Vec::with_capacity(1_000);
613    for idx in 0..1_000u32 {
614        signals.push(Signal::new(idx));
615    }
616    let signals_mount: Vec<Signal<u32>> = signals.clone();
617    let _: NodeId = app.mount(move || {
618        let derived_memos: Vec<Memo<u32>> = signals_mount
619            .into_iter()
620            .map(|sig: Signal<u32>| Memo::new(move || sig.get().wrapping_mul(3).wrapping_add(1)))
621            .collect();
622        view! {
623            scroll {
624                width: Length::Percent(100.0)
625                height: Length::Percent(100.0)
626                gap: 2.0
627                for derived in derived_memos.into_iter() {
628                    text {
629                        font_size: 12.0
630                        color: p.get_foreground()
631                        { move || format!("{BENCH_CELL_LABEL} {}", derived.get()) }
632                    }
633                }
634            }
635        }
636    });
637    let _: Result<FrameStats, PlatformError> = app.step_frame();
638    let start: Instant = Instant::now();
639    let mut last_rev: u64 = 0;
640    for tick in 1..=(count as u32) {
641        batch(|| {
642            for (idx, sig) in signals.iter().enumerate() {
643                let _: bool = sig.set_if_changed(tick.wrapping_add(idx as u32));
644            }
645        });
646        flush_effects();
647        if app.step_frame().is_ok() {
648            last_rev = app.get_last_rendered_revision();
649        }
650    }
651    build_metric(
652        BENCH_STRESS_BULK_REACTIVE_NAME,
653        count,
654        start.elapsed(),
655        format!("components=1000 final_rev={last_rev}"),
656    )
657}
658
659/// Stress-benchmarks end-to-end dynamic `.wasm` binary verification, sandbox execution, hot-swap, and rollback cycles.
660///
661/// # Arguments
662///
663/// - `usize` - Number of v1 -> v2 -> rollback hot-swap cycles to measure.
664///
665/// # Returns
666///
667/// - `BenchMetric` - Measured latency per full dynamic WASM hot-swap cycle.
668#[must_use]
669pub fn bench_stress_wasm_dynamic_hotswap(iterations: usize) -> BenchMetric {
670    reset_reactive_runtime();
671    let count: usize = iterations.max(1);
672    let mut win: WindowConfig = WindowConfig::default();
673    win.set_size(640, 480).set_render(RenderConfig::hardware());
674    let mut cfg: AppConfig = AppConfig::default();
675    cfg.set_window(win);
676    let Ok(mut app) = App::headless(cfg) else {
677        return build_metric(
678            BENCH_STRESS_WASM_LOAD_NAME,
679            count,
680            Duration::ZERO,
681            String::new(),
682        );
683    };
684    let hub: DynamicUpdateHub = app.get_dynamic_hub().clone();
685    let registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
686    let wasm_v1: Vec<u8> = build_partial_widget_wasm(BENCH_WASM_TITLE_V1, 1, 0x2563EB);
687    let wasm_v2: Vec<u8> = build_partial_widget_wasm(BENCH_WASM_TITLE_V2, 2, 0x7C3AED);
688    let csum_v1: u64 = compute_wasm_checksum(&wasm_v1);
689    let csum_v2: u64 = compute_wasm_checksum(&wasm_v2);
690    registry.register(
691        BENCH_WASM_URL_V1.to_string(),
692        wasm_v1,
693        BENCH_WASM_ETAG_V1.to_string(),
694        WasmFaultKind::None,
695    );
696    registry.register(
697        BENCH_WASM_URL_V2.to_string(),
698        wasm_v2,
699        BENCH_WASM_ETAG_V2.to_string(),
700        WasmFaultKind::None,
701    );
702    let manager: WasmDynamicManager =
703        WasmDynamicManager::new(hub.clone(), Rc::new(registry), WasmSandboxConfig::default());
704    let hub_slot: DynamicUpdateHub = hub;
705    let _: NodeId = app.mount(move || {
706        view! {
707            slot {
708                id: BENCH_WASM_SLOT
709                hub: hub_slot
710                text {
711                    font_size: 14.0
712                    { BENCH_TITLE }
713                }
714            }
715        }
716    });
717    let _: Result<FrameStats, PlatformError> = app.step_frame();
718    let start: Instant = Instant::now();
719    let mut completed: usize = 0;
720    for cycle in 0..count {
721        let base_ver: u64 = ((cycle as u64) * 2) + 1;
722        let req_v1: WasmDownloadRequest = WasmDownloadRequest::partial(
723            BENCH_WASM_URL_V1.to_string(),
724            BENCH_WASM_SLOT.to_string(),
725            base_ver,
726        )
727        .with_checksum(csum_v1)
728        .with_allow_downgrade(true);
729        let req_v2: WasmDownloadRequest = WasmDownloadRequest::partial(
730            BENCH_WASM_URL_V2.to_string(),
731            BENCH_WASM_SLOT.to_string(),
732            base_ver + 1,
733        )
734        .with_checksum(csum_v2)
735        .with_allow_downgrade(true);
736        if manager.load_and_mount(req_v1, BENCH_WASM_SIGN_KEY).is_ok()
737            && manager.load_and_mount(req_v2, BENCH_WASM_SIGN_KEY).is_ok()
738            && manager
739                .rollback_partial(BENCH_WASM_SLOT, BENCH_WASM_ROLLBACK_REASON)
740                .is_ok()
741        {
742            let _: Result<FrameStats, PlatformError> = app.step_frame();
743            completed += 1;
744        }
745    }
746    build_metric(
747        BENCH_STRESS_WASM_LOAD_NAME,
748        count,
749        start.elapsed(),
750        format!("cycles={completed} cache={}", manager.cache_len()),
751    )
752}
753
754/// Stress-benchmarks flagship mobile `1440x3168 @ 4.0x` multi-card shadowed UI scrolling in the multi-core software rasterizer.
755///
756/// # Arguments
757///
758/// - `usize` - Number of full scrolled 4x-DPI frames to measure.
759///
760/// # Returns
761///
762/// - `BenchMetric` - Measured frame latency and FPS throughput at `1440x3168`.
763#[must_use]
764pub fn bench_stress_hidpi_4x_1440x3168(iterations: usize) -> BenchMetric {
765    reset_reactive_runtime();
766    let count: usize = iterations.max(1);
767    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
768    let mut win: WindowConfig = WindowConfig::default();
769    win.set_size(360, 792).set_render(RenderConfig::software());
770    let mut cfg: AppConfig = AppConfig::default();
771    cfg.set_window(win);
772    let Ok(mut app) = App::headless(cfg) else {
773        return build_metric(
774            BENCH_STRESS_HIDPI_4X_NAME,
775            count,
776            Duration::ZERO,
777            String::new(),
778        );
779    };
780    let mut scroll_id: NodeId = NodeId::default();
781    let _: NodeId = app.mount(|| {
782        view! {
783            scroll {
784                node_ref: scroll_id
785                width: Length::Percent(100.0)
786                height: Length::Percent(100.0)
787                padding: Edges::all(SPACE_MD)
788                gap: SPACE_MD
789                background: tokens.get_palette().get_background()
790                for idx in 0..16usize {
791                    EuvCard {
792                        title: format!("{BENCH_TITLE} #{idx}")
793                        tokens: tokens
794                        subtitle: BENCH_CARD_CAPTION
795                        EuvBadge {
796                            label: BENCH_BADGE.to_string()
797                            tone: EuvTone::Primary
798                            tokens: tokens
799                        }
800                        EuvProgress {
801                            value: ((idx % 9) as f32 + 1.0) * 0.1
802                            tokens: tokens
803                        }
804                    }
805                }
806            }
807        }
808    });
809    app.set_exact_physical_viewport(1440, 3168, 4.0);
810    let _: Result<FrameStats, PlatformError> = app.step_frame();
811    let start: Instant = Instant::now();
812    let mut last_shaded: usize = 0;
813    for step in 1..=count {
814        let offset_y: f32 = ((step as f32) * 18.5) % 800.0;
815        app.get_scene().with_write(
816            |tree: &mut SceneTree| {
817                tree.set_scroll_offset(scroll_id, Point::new(0.0, offset_y));
818            },
819            (),
820        );
821        if let Ok(stats) = app.step_frame() {
822            last_shaded = stats.get_pixels_shaded();
823        }
824    }
825    build_metric(
826        BENCH_STRESS_HIDPI_4X_NAME,
827        count,
828        start.elapsed(),
829        format!("res=1440x3168@4x shaded={last_shaded}"),
830    )
831}
832
833/// Stress-benchmarks 240Hz touch-pan scroll physics, thumb-lift anti-reversal filtering, and 1,000-node scene hit-testing.
834///
835/// # Arguments
836///
837/// - `usize` - Number of 240Hz input/hit-test ticks to measure.
838///
839/// # Returns
840///
841/// - `BenchMetric` - Measured input + hit-test latency and throughput.
842#[must_use]
843pub fn bench_stress_scroll_physics_and_hittest(iterations: usize) -> BenchMetric {
844    reset_reactive_runtime();
845    let count: usize = iterations.max(1);
846    let mut win: WindowConfig = WindowConfig::default();
847    win.set_size(360, 792).set_render(RenderConfig::hardware());
848    let mut cfg: AppConfig = AppConfig::default();
849    cfg.set_window(win);
850    let Ok(mut app) = App::headless(cfg) else {
851        return build_metric(
852            BENCH_STRESS_INPUT_HITTEST_NAME,
853            count,
854            Duration::ZERO,
855            String::new(),
856        );
857    };
858    let _: NodeId = app.mount(|| {
859        view! {
860            scroll {
861                width: Length::Percent(100.0)
862                height: Length::Percent(100.0)
863                gap: 4.0
864                for idx in 0..1_000usize {
865                    row {
866                        width: Length::Percent(100.0)
867                        height: Length::Px(32.0)
868                        cursor: CursorIcon::Pointer
869                        text {
870                            { format!("{BENCH_ROW_LABEL} {idx}") }
871                        }
872                    }
873                }
874            }
875        }
876    });
877    let wid: WindowId = app.get_window_state().get_id();
878    let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 120.0);
879    let start: Instant = Instant::now();
880    let mut hits: usize = 0;
881    app.dispatch_window_event(WindowEvent::PointerDown(
882        wid,
883        PointerEvent::touch(1, 180.0, 620.0),
884    ));
885    for step in 0..count {
886        let y: f32 = 620.0 - ((step % 48) as f32) * 8.0;
887        app.dispatch_window_event(WindowEvent::PointerMove(
888            wid,
889            PointerEvent::touch(1, 180.0, y),
890        ));
891        let found: bool = app.get_scene().with_read(
892            |tree: &SceneTree| hit_test(tree, Point::new(180.0, 320.0)).is_some(),
893            false,
894        );
895        if found {
896            hits += 1;
897        }
898        if step % 2 == 0 {
899            let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
900        }
901    }
902    app.dispatch_window_event(WindowEvent::PointerUp(
903        wid,
904        PointerEvent::touch(1, 180.0, 240.0),
905    ));
906    build_metric(
907        BENCH_STRESS_INPUT_HITTEST_NAME,
908        count,
909        start.elapsed(),
910        format!("nodes=1000 hits={hits}"),
911    )
912}
913
914/// Runs the complete reproducible benchmark and stress-test suite across reactivity, layout, virtual lists, WASM OTA, high-DPI rendering, input, and game physics.
915///
916/// # Returns
917///
918/// - `BenchReport` - Aggregated benchmark results.
919#[must_use]
920pub fn run_full_benchmark_suite() -> BenchReport {
921    let metrics: Vec<BenchMetric> = vec![
922        bench_reactive_signals_and_memos(10_000),
923        bench_selector_o1(10_000),
924        bench_layout_cache(1_000),
925        bench_unicode_glyph_atlas(100),
926        bench_software_full_redraw(20),
927        bench_software_rasterizer(20),
928        bench_hardware_gpu_batching(200),
929        bench_game_ecs_physics(200),
930        bench_game_particles(1_000),
931        bench_game3d_pbr_bvh_raytrace(10),
932        bench_game3d_cinematic_max_rt(10),
933        bench_stress_long_list_100k(30),
934        bench_stress_complex_layout_2000(40),
935        bench_stress_bulk_reactive_1000(20),
936        bench_stress_wasm_dynamic_hotswap(30),
937        bench_stress_hidpi_4x_1440x3168(15),
938        bench_stress_scroll_physics_and_hittest(240),
939    ];
940    BenchReport::new(metrics)
941}
942
943/// Formats a `BenchReport` into an aligned terminal summary table.
944///
945/// # Arguments
946///
947/// - `&BenchReport` - Completed benchmark report.
948///
949/// # Returns
950///
951/// - `String` - Human-readable report table.
952#[must_use]
953pub fn format_bench_report(report: &BenchReport) -> String {
954    let mut out: String = String::from(REPORT_HEADER);
955    for m in report.get_metrics().iter() {
956        out.push_str(&format!(
957            "{:32} iters={:6} avg={:10.1} ns/op  throughput={:10.0} ops/s  {}\n",
958            m.get_name(),
959            m.get_iterations(),
960            m.get_ns_per_op(),
961            m.get_ops_per_sec(),
962            m.get_detail()
963        ));
964    }
965    out
966}
967
968/// Serializes a `BenchReport` to formatted JSON.
969///
970/// # Arguments
971///
972/// - `&BenchReport` - Completed benchmark report.
973///
974/// # Returns
975///
976/// - `String` - Pretty-printed JSON string.
977#[must_use]
978pub fn report_to_json(report: &BenchReport) -> String {
979    to_string_pretty(report).unwrap_or_default()
980}
981
982/// Shared rendering benchmark harness supporting both Software and Hardware modes.
983///
984/// # Arguments
985///
986/// - `&str` - Benchmark name.
987/// - `RenderConfig` - Renderer pipeline configuration.
988/// - `usize` - Number of frames to step.
989///
990/// # Returns
991///
992/// - `BenchMetric` - Measured frame telemetry.
993fn bench_render_pipeline(name: &str, render: RenderConfig, iterations: usize) -> BenchMetric {
994    reset_reactive_runtime();
995    let count: usize = iterations.max(1);
996    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
997    let mut win: WindowConfig = WindowConfig::default();
998    win.set_size(800, 600).set_render(render);
999    let mut cfg: AppConfig = AppConfig::default();
1000    cfg.set_window(win);
1001    let Ok(mut app) = App::headless(cfg) else {
1002        return build_metric(name, count, Duration::ZERO, String::new());
1003    };
1004    let _: NodeId = app.mount(|| {
1005        view! {
1006            column {
1007                width: Length::Percent(100.0)
1008                padding: Edges::all(SPACE_LG)
1009                gap: SPACE_MD
1010                EuvHeader {
1011                    title: BENCH_TITLE.to_string()
1012                    subtitle: BENCH_SUBTITLE.to_string()
1013                    tokens: tokens
1014                }
1015                EuvCard {
1016                    title: BENCH_TITLE.to_string()
1017                    tokens: tokens
1018                    subtitle: BENCH_SUBTITLE
1019                    EuvBadge {
1020                        label: BENCH_BADGE.to_string()
1021                        tone: EuvTone::Primary
1022                        tokens: tokens
1023                    }
1024                    EuvProgress {
1025                        value: 0.72
1026                        tokens: tokens
1027                    }
1028                }
1029            }
1030        }
1031    });
1032    let start: Instant = Instant::now();
1033    let mut last_hash: u64 = 0;
1034    let mut last_batches: usize = 0;
1035    for _ in 0..count {
1036        if let Ok(stats) = app.step_frame() {
1037            last_hash = stats.get_frame_hash();
1038            last_batches = stats.get_draw_batches();
1039        }
1040    }
1041    build_metric(
1042        name,
1043        count,
1044        start.elapsed(),
1045        format!("batches={last_batches} hash={last_hash:#018x}"),
1046    )
1047}
1048
1049/// Constructs a `BenchMetric` from elapsed wall time and iteration count.
1050///
1051/// # Arguments
1052///
1053/// - `&str` - Metric name.
1054/// - `usize` - Completed iterations.
1055/// - `Duration` - Total elapsed time.
1056/// - `String` - Extra metadata string.
1057///
1058/// # Returns
1059///
1060/// - `BenchMetric` - Computed timing metric.
1061fn build_metric(name: &str, iterations: usize, elapsed: Duration, detail: String) -> BenchMetric {
1062    let total_nanos: f64 = elapsed.as_nanos().max(1) as f64;
1063    let ns_per_op: f64 = total_nanos / (iterations.max(1) as f64);
1064    let ops_per_sec: f64 = 1_000_000_000.0 / ns_per_op.max(1.0);
1065    BenchMetric::new(
1066        name.to_string(),
1067        iterations,
1068        elapsed.as_micros() as u64,
1069        ns_per_op,
1070        ops_per_sec,
1071        detail,
1072    )
1073}