//! Render benchmarks for `rustik-diff`. //! //! The benchmark decodes deterministic unified diffs once, then exercises //! render, scroll, resize, focus, highlight-request, and highlight-refresh paths. use std::hint::black_box; use std::io::{self, Write as _}; use std::str::FromStr; use std::time::{Duration, Instant}; use rustik_diff::{ BuiltinHighlighter, Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer, HighlightRequest, HighlightResult, }; use rustik_highlight as syntax; use rustik_tui::{ Buffer, Color, Constraint, Label, Line, Rect, Scroll, Style, Table, TableOptions, }; /// Fixed terminal-sized render area. const AREA: Rect = Rect::new(0, 0, 120, 40); /// Narrow terminal area used by resize-heavy scenarios. const NARROW_AREA: Rect = Rect::new(0, 0, 80, 24); /// Wide terminal area used by resize-heavy scenarios. const WIDE_AREA: Rect = Rect::new(0, 0, 180, 50); /// Tiny terminal area used to stress minimum-width rendering. const TINY_AREA: Rect = Rect::new(0, 0, 44, 12); /// Default frame count. const DEFAULT_FRAMES: usize = 80; /// Default frame count for expensive real syntax-highlight landing runs. const DEFAULT_HIGHLIGHT_FRAMES: usize = 3; /// Default frame count for each workload in the full suite. const DEFAULT_SUITE_FRAMES: usize = DEFAULT_FRAMES; /// Default number of independent timed runs per workload. const DEFAULT_RUNS: usize = 3; /// Default number of file sections in the generated diff. const DEFAULT_FILES: usize = 32; /// Default number of hunk lines per generated file. const DEFAULT_LINES: usize = 128; /// One row sample stride for the checksum. const SAMPLE_ROWS: usize = 5; /// One column sample stride for the checksum. const SAMPLE_COLS: usize = 7; /// Low-emphasis report text color. const REPORT_DIM: Color = Color::Fixed(244); /// Theme name used by the interactive pager. const THEME_NAME: &str = "rustik-catppuccin-mocha"; /// Built-in syntax theme JSON used by the interactive pager. const THEME: &str = include_str!("../src/themes/rustik-catppuccin-mocha.json"); /// Runs the benchmark. fn main() { let args = Args::parse(); let workloads = args.workload.expanded(); let report_widths = ReportWidths::new(&workloads); let mut checksum = 0usize; for workload in workloads { let report = run_workload(workload, args); checksum ^= report.checksum.rotate_left(report.workload as u32); report_workload(&report, report_widths); black_box(report); } black_box(checksum); } /// Benchmark command-line arguments. #[derive(Clone, Copy, Debug)] struct Args { /// Workload to run. workload: Workload, /// Number of frames to render. frames: FrameCount, /// Number of independent timed runs per workload. runs: usize, /// Number of synthetic file sections. files: usize, /// Number of synthetic hunk lines per file. lines: usize, } impl Args { /// Parses benchmark arguments from the process environment. fn parse() -> Self { Self::parse_from(std::env::args().skip(1)) } /// Parses benchmark arguments from an iterator. fn parse_from(args: impl IntoIterator) -> Self { let mut parsed = Self { workload: Workload::All, frames: FrameCount::Default, runs: DEFAULT_RUNS, files: DEFAULT_FILES, lines: DEFAULT_LINES, }; let mut args = args.into_iter(); while let Some(arg) = args.next() { match arg.as_str() { "--workload" | "-w" => parsed.workload = next_workload(&mut args, parsed.workload), "--frames" => { parsed.frames = FrameCount::Explicit(next_usize(&mut args, DEFAULT_FRAMES)); } "--runs" => parsed.runs = next_usize(&mut args, parsed.runs).max(1), "--files" => parsed.files = next_usize(&mut args, parsed.files), "--lines" => parsed.lines = next_usize(&mut args, parsed.lines), "--help" | "-h" => { println!( "usage: cargo bench -p rustik-diff --bench render -- [--workload NAME] [--runs N] [--frames N] [--files N] [--lines N]" ); std::process::exit(0); } value => { if let Ok(value) = value.parse() { parsed.frames = FrameCount::Explicit(value); } } } } parsed } } /// Frame-count selection mode. #[derive(Clone, Copy, Debug)] enum FrameCount { /// Use workload-sensitive defaults. Default, /// Use the same explicit frame count for every selected workload. Explicit(usize), } impl FrameCount { /// Returns the concrete frame count for one workload. const fn for_workload(self, requested: Workload) -> usize { match (self, requested) { (Self::Default, Workload::Highlight) => DEFAULT_HIGHLIGHT_FRAMES, (Self::Default, Workload::All) => DEFAULT_SUITE_FRAMES, (Self::Default, _) => DEFAULT_FRAMES, (Self::Explicit(frames), _) => frames, } } } /// Named benchmark workload. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum Workload { /// Original fixed-area, warm-cache, one-line scroll workload. WarmScroll, /// Mixed pager session with scrolling, navigation, and resize. Session, /// Width-changing render workload. Resize, /// Scrolling offsets concentrated around file boundaries. Sticky, /// Visible syntax-highlight landing workload. Highlight, /// Visible highlight request scheduling without drawing rows. HighlightRequests, /// Steady-state render of word-diff overlays on a warm highlight cache. WordDiff, /// Large file-count workload with short hunks. ManyFiles, /// Single huge file workload. HugeFile, /// Long and Unicode-heavy source line workload. LongLines, /// Runs every named workload. All, } impl Workload { /// Returns concrete workloads represented by this value. fn expanded(self) -> Vec { match self { Self::All => vec![ Self::WarmScroll, Self::Session, Self::Resize, Self::Sticky, Self::Highlight, Self::HighlightRequests, Self::WordDiff, Self::ManyFiles, Self::HugeFile, Self::LongLines, ], workload => vec![workload], } } /// Returns the workload display name. const fn name(self) -> &'static str { match self { Self::WarmScroll => "warm-scroll", Self::Session => "session", Self::Resize => "resize", Self::Sticky => "sticky", Self::Highlight => "highlight", Self::HighlightRequests => "highlight-requests", Self::WordDiff => "word-diff", Self::ManyFiles => "many-files", Self::HugeFile => "huge-file", Self::LongLines => "long-lines", Self::All => "all", } } /// Returns the report unit measured by the workload. const fn metric_unit(self) -> &'static str { match self { Self::HighlightRequests => "tps", Self::Highlight => "ms/land", Self::WarmScroll | Self::Session | Self::Resize | Self::Sticky | Self::WordDiff | Self::ManyFiles | Self::HugeFile | Self::LongLines | Self::All => "fps", } } /// Converts an elapsed workload run into the reported metric. fn metric_value(self, elapsed: Duration, frames: usize) -> f64 { let frames = frames.max(1); match self { Self::Highlight => elapsed.as_secs_f64() * 1_000.0 / frames as f64, _ => frames as f64 / elapsed.as_secs_f64(), } } /// Returns the synthetic document shape for the workload. fn document_shape(self, args: Args) -> DiffShape { match self { Self::ManyFiles => DiffShape { files: args.files.max(1_024), lines: 12, hunk_lines: 6, profile: LineProfile::Tiny, }, Self::HugeFile => DiffShape { files: 1, lines: args.lines.max(16_384), hunk_lines: 256, profile: LineProfile::Normal, }, Self::LongLines => DiffShape { files: args.files, lines: args.lines, hunk_lines: 64, profile: LineProfile::LongUnicode, }, Self::Highlight => { let lines = args.lines.max(16_384); DiffShape { files: 1, lines, hunk_lines: lines, profile: LineProfile::Normal, } } Self::Sticky => DiffShape { files: args.files.max(256), lines: 32, hunk_lines: 16, profile: LineProfile::Normal, }, Self::Session | Self::Resize | Self::HighlightRequests | Self::WordDiff | Self::WarmScroll | Self::All => DiffShape { files: args.files, lines: args.lines, hunk_lines: 64, profile: LineProfile::Normal, }, } } } impl FromStr for Workload { type Err = (); fn from_str(value: &str) -> Result { match value { "warm-scroll" | "plain" | "scroll" => Ok(Self::WarmScroll), "session" => Ok(Self::Session), "resize" => Ok(Self::Resize), "sticky" | "sticky-boundaries" => Ok(Self::Sticky), "highlight" | "highlights" => Ok(Self::Highlight), "highlight-requests" | "requests" => Ok(Self::HighlightRequests), "word-diff" | "worddiff" => Ok(Self::WordDiff), "many-files" => Ok(Self::ManyFiles), "huge-file" => Ok(Self::HugeFile), "long-lines" => Ok(Self::LongLines), "all" => Ok(Self::All), _ => Err(()), } } } /// Shape of a generated diff document. #[derive(Clone, Copy, Debug)] struct DiffShape { /// Number of files to generate. files: usize, /// Number of source rows to generate per file. lines: usize, /// Maximum number of rows per hunk. hunk_lines: usize, /// Source-line content profile. profile: LineProfile, } /// Source-line text profile. #[derive(Clone, Copy, Debug)] enum LineProfile { /// Short Rust-like lines. Normal, /// Very small hunks for many-file workloads. Tiny, /// Wide rows with Unicode graphemes. LongUnicode, } /// Result from one workload run. #[derive(Clone, Copy, Debug)] struct BenchReport { /// Workload that produced the report. workload: Workload, /// Workload metric statistics across independent runs. metric: RepeatStats, /// Combined deterministic render checksum across independent runs. checksum: usize, } /// Summary statistics for repeated benchmark runs. #[derive(Clone, Copy, Debug)] struct RepeatStats { /// Average reported workload value. avg: f64, /// Reported workload value standard deviation. stddev: f64, } /// Report column widths derived before workloads run. #[derive(Clone, Copy, Debug)] struct ReportWidths { /// Widest selected workload name. workload: usize, /// Width reserved for formatted workload metrics. metric: usize, } /// Widest expected workload-metric value used to keep streaming rows aligned. const METRIC_FORMAT: &str = "000000.0"; /// Parses the next argument as a `usize`. fn next_usize(args: &mut impl Iterator, fallback: usize) -> usize { args.next() .and_then(|value| value.parse().ok()) .unwrap_or(fallback) } /// Parses the next argument as a workload. fn next_workload(args: &mut impl Iterator, fallback: Workload) -> Workload { args.next() .and_then(|value| value.parse().ok()) .unwrap_or(fallback) } /// Runs one named benchmark workload. fn run_workload(workload: Workload, args: Args) -> BenchReport { let frames = args.frames.for_workload(workload); let shape = workload.document_shape(args); let input = synthetic_diff(shape); let document = match DiffDocument::decode_str(&input) { Ok(document) => document, Err(error) => { eprintln!("failed to decode generated benchmark diff: {error}"); std::process::exit(1); } }; let rows = rustik_tui::Widget::size( &DiffViewer::new(document.clone(), DiffOptions::default()), Constraint::UNBOUNDED, ) .rows; let mut metrics = Vec::with_capacity(args.runs); let mut checksum = rows; for run in 0..args.runs { let (run_elapsed, run_checksum) = run_once(workload, document.clone(), frames); metrics.push(workload.metric_value(run_elapsed, frames)); checksum ^= run_checksum.rotate_left((run % usize::BITS as usize) as u32); } BenchReport { workload, metric: RepeatStats::from_values(&metrics), checksum, } } /// Runs one independent timed pass for a workload. fn run_once(workload: Workload, document: DiffDocument, frames: usize) -> (Duration, usize) { match workload { Workload::WarmScroll => run_warm_scroll(document, frames), Workload::Session => run_session(document, frames), Workload::Resize => run_resize(document, frames), Workload::Sticky => run_sticky(document, frames), Workload::Highlight => run_highlight(document, frames), Workload::HighlightRequests => run_highlight_requests(document, frames), Workload::WordDiff => run_word_diff(document, frames), Workload::ManyFiles => run_session(document, frames), Workload::HugeFile => run_sticky(document, frames), Workload::LongLines => run_resize(document, frames), Workload::All => unreachable!("run_once: all is expanded before dispatch"), } } /// Renders a fixed-area warm-cache scrolling workload. fn run_warm_scroll(document: DiffDocument, frames: usize) -> (Duration, usize) { let mut viewer = DiffViewer::new(document, DiffOptions::default()); let mut buffer = Buffer::empty(AREA); let start = Instant::now(); let mut checksum = 0usize; for frame in 0..frames { buffer.clear(); viewer.render(AREA, &mut buffer); checksum ^= sample_buffer(&buffer, frame); viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA); buffer.reset_dirty(); } (start.elapsed(), checksum) } /// Renders a mixed pager session. fn run_session(document: DiffDocument, frames: usize) -> (Duration, usize) { let areas = [AREA, AREA, WIDE_AREA, AREA, NARROW_AREA, AREA]; run_scripted(document, frames, |viewer, frame| { let area = areas[frame % areas.len()]; match frame % 24 { 0 => apply_resize(viewer, area), 1..=6 => { viewer.apply(DiffAction::Scroll(Scroll::Lines(3)), area); } 7 => { viewer.apply( DiffAction::Scroll(Scroll::Lines((area.rows / 2) as isize)), area, ); } 8 => { viewer.apply(DiffAction::NextHunk, area); } 9 => { viewer.apply(DiffAction::FocusNext, area); } 10 => { viewer.apply(DiffAction::FocusPrevious, area); } 11 => { viewer.apply(DiffAction::NextHunk, area); } 12 => { viewer.apply(DiffAction::PreviousHunk, area); } _ => { viewer.apply(DiffAction::Scroll(Scroll::Lines(-1)), area); } } area }) } /// Renders while invalidating width-dependent caches with resize events. fn run_resize(document: DiffDocument, frames: usize) -> (Duration, usize) { let areas = [AREA, WIDE_AREA, NARROW_AREA, TINY_AREA, AREA]; run_scripted(document, frames, |viewer, frame| { let area = areas[frame % areas.len()]; apply_resize(viewer, area); viewer.apply( DiffAction::Scroll(Scroll::Lines((frame % 7) as isize - 3)), area, ); area }) } /// Renders offsets concentrated around sticky file-header transitions. fn run_sticky(document: DiffDocument, frames: usize) -> (Duration, usize) { run_scripted(document, frames, |viewer, frame| { if frame % 16 == 0 { viewer.apply(DiffAction::FocusNext, AREA); } else if frame % 16 < 8 { viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA); } else { viewer.apply(DiffAction::Scroll(Scroll::Lines(-1)), AREA); } AREA }) } /// Renders until visible rows have real syntax highlights applied. fn run_highlight(document: DiffDocument, frames: usize) -> (Duration, usize) { let mut viewer = DiffViewer::new(document, DiffOptions::default()); let mut buffer = Buffer::empty(AREA); let rows = rustik_tui::Widget::size(&viewer, Constraint::UNBOUNDED).rows; viewer.apply(DiffAction::Scroll(Scroll::Lines((rows / 2) as isize)), AREA); let start = Instant::now(); let raw_theme = match THEME.parse::() { Ok(theme) => theme, Err(error) => { eprintln!("failed to parse benchmark theme: {error:?}"); std::process::exit(1); } }; let mut raw = match syntax::syntaxes::RUST.parse::() { Ok(raw) => raw, Err(error) => { eprintln!("failed to parse benchmark grammar: {error:?}"); std::process::exit(1); } }; if !raw .file_types .iter() .any(|existing| existing.eq_ignore_ascii_case("rs")) { raw.file_types.push("rs".to_owned()); } let rust_grammar = match syntax::Grammar::compile_with(&raw, &[]) { Ok(grammar) => grammar, Err(error) => { eprintln!("failed to compile benchmark grammar: {error:?}"); std::process::exit(1); } }; let mut registry = syntax::Registry::default(); registry.add_theme(syntax::Theme::compile(&raw_theme)); registry.add_grammar(rust_grammar); let mut highlighter = BuiltinHighlighter::new(registry, THEME_NAME); let mut checksum = 0usize; for frame in 0..frames { buffer.clear(); viewer.render(AREA, &mut buffer); checksum ^= sample_buffer(&buffer, frame); let requests = viewer.visible_highlight_requests(AREA); let results = highlighter.highlight_requests(requests); viewer.apply_highlights(results); buffer.clear(); viewer.render(AREA, &mut buffer); checksum ^= sample_buffer(&buffer, frame.wrapping_add(frames)); viewer.apply( DiffAction::Scroll(Scroll::Lines((frame % 5 + 1) as isize)), AREA, ); buffer.reset_dirty(); } (start.elapsed(), checksum) } /// Renders cached word-diff overlays with a warm highlight cache. /// /// Pre-applies synthetic highlight results for the rows the workload will /// scroll across, then measures render+scroll cost on already-overlaid lines. /// Because every `-/+` pair in `synthetic_diff` passes the word-diff similarity /// gate, this isolates the cached-render fast path that /// [`DiffViewer::apply_highlights`] now bakes the overlay into. fn run_word_diff(document: DiffDocument, frames: usize) -> (Duration, usize) { let mut viewer = DiffViewer::new(document, DiffOptions::default()); let mut buffer = Buffer::empty(AREA); let span = AREA.rows.saturating_mul(2) as isize; // Walk forward across the scroll span so every row we'll visit gets a // highlight result. Then walk back to the start before timing begins. for _ in 0..span { let requests = viewer.highlight_requests(AREA); viewer.apply_highlights(requests.into_iter().map(highlight_result)); viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA); } viewer.apply(DiffAction::Scroll(Scroll::Lines(-span)), AREA); let start = Instant::now(); let mut checksum = 0usize; for frame in 0..frames { buffer.clear(); viewer.render(AREA, &mut buffer); checksum ^= sample_buffer(&buffer, frame); let step = if (frame as isize / span) % 2 == 0 { 1 } else { -1 }; viewer.apply(DiffAction::Scroll(Scroll::Lines(step)), AREA); buffer.reset_dirty(); } (start.elapsed(), checksum) } /// Schedules visible highlight requests without drawing rendered rows. fn run_highlight_requests(document: DiffDocument, frames: usize) -> (Duration, usize) { let mut viewer = DiffViewer::new(document, DiffOptions::default()); let start = Instant::now(); let mut checksum = 0usize; for frame in 0..frames { let requests = viewer.highlight_requests(AREA); checksum ^= sample_requests(&requests, frame); viewer.apply( DiffAction::Scroll(Scroll::Lines((frame % 5 + 1) as isize)), AREA, ); } (start.elapsed(), checksum) } /// Renders frames using a caller-provided action script. fn run_scripted( document: DiffDocument, frames: usize, mut script: impl FnMut(&mut DiffViewer, usize) -> Rect, ) -> (Duration, usize) { let mut viewer = DiffViewer::new(document, DiffOptions::default()); let mut buffer = Buffer::empty(AREA); let start = Instant::now(); let mut checksum = 0usize; for frame in 0..frames { let area = script(&mut viewer, frame); buffer.resize(area); buffer.clear(); viewer.render(area, &mut buffer); checksum ^= sample_buffer(&buffer, frame); buffer.reset_dirty(); } (start.elapsed(), checksum) } /// Applies resize handling for an area. fn apply_resize(viewer: &mut DiffViewer, area: Rect) { viewer.apply(DiffAction::Resize, area); } /// Converts a highlight request into a deterministic synthetic result. fn highlight_result(request: HighlightRequest) -> HighlightResult { let line = Line::new( Label::from( request .source .line(request.key.source_line) .unwrap_or_default(), ) .fg(Color::Yellow), ); HighlightResult::new(request, line) } /// Creates a deterministic Git-style unified diff. fn synthetic_diff(shape: DiffShape) -> String { let mut diff = String::new(); for file in 0..shape.files { diff.push_str(&format!( "diff --git a/src/file_{file:04}.rs b/src/file_{file:04}.rs\n" )); diff.push_str(&format!("index {file:040x}..{:040x} 100644\n", file + 1)); diff.push_str(&format!("--- a/src/file_{file:04}.rs\n")); diff.push_str(&format!("+++ b/src/file_{file:04}.rs\n")); let mut old_start = 1usize; let mut new_start = 1usize; for hunk_start in (0..shape.lines).step_by(shape.hunk_lines.max(1)) { let hunk_lines = shape.hunk_lines.min(shape.lines - hunk_start); let hunk_range = hunk_start..hunk_start + hunk_lines; let additions = hunk_range.clone().filter(|line| line % 5 == 1).count(); let deletions = hunk_range.filter(|line| line % 5 == 0).count(); let context = hunk_lines.saturating_sub(additions + deletions); let old_lines = deletions + context; let new_lines = additions + context; diff.push_str(&format!( "@@ -{old_start},{old_lines} +{new_start},{new_lines} @@ fn file_{file:04}_hunk_{hunk_start:04}()\n" )); for line in hunk_start..hunk_start + hunk_lines { push_diff_line(&mut diff, shape.profile, file, line); } old_start += old_lines + 8; new_start += new_lines + 8; } } diff } /// Adds one generated diff line. fn push_diff_line(diff: &mut String, profile: LineProfile, file: usize, line: usize) { let prefix = match line % 5 { 0 => '-', 1 => '+', _ => ' ', }; diff.push(prefix); diff.push_str(&line_text(profile, file, line)); diff.push('\n'); } /// Returns one generated source line. fn line_text(profile: LineProfile, file: usize, line: usize) -> String { match profile { LineProfile::Normal => match line % 5 { 0 => format!("let old_value_{line:04} = compute({file}, {line});"), 1 => format!("let new_value_{line:04} = compute_fast({file}, {line});"), _ => format!("let stable_value_{line:04} = keep({file}, {line});"), }, LineProfile::Tiny => format!("v{file}_{line}();"), LineProfile::LongUnicode => format!( "let sample_{line:04} = \"file={file} row={line} λ ❤️ {}\";", "payload_segment::".repeat(line % 19 + 12) ), } } /// Samples a buffer for a deterministic checksum. fn sample_buffer(buffer: &Buffer, frame: usize) -> usize { let area = buffer.area(); let mut checksum = frame; for row in (0..area.rows).step_by(SAMPLE_ROWS) { for col in (0..area.cols).step_by(SAMPLE_COLS) { if let Some(cell) = buffer.get(area.x + col, area.y + row) { checksum = checksum.wrapping_mul(16_777_619) ^ cell.glyph().len(); checksum ^= color_id(cell.style().fg_color()); checksum ^= color_id(cell.style().bg_color()).rotate_left(7); } } } checksum } /// Samples highlight requests for a deterministic checksum. fn sample_requests(requests: &[HighlightRequest], frame: usize) -> usize { requests .iter() .fold(frame ^ requests.len(), |checksum, request| { checksum ^ request.key.text_hash as usize ^ request.source.text.len() ^ request .path .as_ref() .map_or(0, |path| path.as_os_str().len()) }) } /// Returns a stable numeric id for a color. fn color_id(color: Color) -> usize { match color { Color::Unset => 0, Color::Black => 1, Color::Red => 2, Color::Green => 3, Color::Yellow => 4, Color::Blue => 5, Color::Magenta => 6, Color::Cyan => 7, Color::White => 8, Color::Fixed(value) => 0x100 + usize::from(value), Color::RGB(r, g, b) => { 0x1_0000 + (usize::from(r) << 16) + (usize::from(g) << 8) + usize::from(b) } } } /// Prints one styled workload report line. fn report_workload(report: &BenchReport, widths: ReportWidths) { let table = Table::new(TableOptions { spacing: 3, ..TableOptions::default() }) .row([ Label::from("x".repeat(widths.workload)), Label::from("0".repeat(widths.metric)), Label::from(format!("±{}", "0".repeat(widths.metric))), ]) .row([ Label::new(report.workload.name()).style(Style::default().bold()), Label::from(format_metric( report.metric.avg, report.workload.metric_unit(), )) .fg(Color::White), Label::from(format!("±{:.1}", report.metric.stddev)).fg(REPORT_DIM), ]); if let Some(line) = table.lines(Constraint::UNBOUNDED).get(1) { println!("{}", line.styled()); } flush_stdout(); } impl ReportWidths { /// Computes report column widths for a selected workload set. fn new(workloads: &[Workload]) -> Self { Self { workload: workloads .iter() .map(|workload| workload.name().len()) .max() .unwrap_or_default(), metric: workloads .iter() .map(|workload| METRIC_FORMAT.len() + 1 + workload.metric_unit().len()) .max() .unwrap_or(METRIC_FORMAT.len() + 1 + "fps".len()), } } } /// Flushes benchmark output after an incremental report. fn flush_stdout() { let _ = io::stdout().flush(); } impl RepeatStats { /// Computes statistics from repeated numeric values. fn from_values(values: &[f64]) -> Self { let count = values.len() as f64; let avg = values.iter().sum::() / count; let variance = values .iter() .map(|value| { let delta = value - avg; delta * delta }) .sum::() / count; Self { avg, stddev: variance.sqrt(), } } } /// Formats a workload report metric. fn format_metric(value: f64, unit: &str) -> String { format!("{value:.1} {unit}") }