report.rs
This file
Path
src/output/report.rs
205 lines · 7.2 KiB · Rust
Last changed by
Compact terminal output on narrow terminalsDavid Peterbefore adoptione8cdbf2
History of this fileTake it
1use std::io::{self, IsTerminal, Write};23use anyhow::{ensure, Result};4use colored::Colorize;56use crate::benchmark::{benchmark_result::BenchmarkResult, measurement::Measurements};7use crate::metric::MetricSelection;8use crate::output::console_writeln;910// Reserve enough space for typical values and every supported unit suffix so11// independently printed benchmarks keep the same layout.12const MIN_VALUE_WIDTH: usize = 7;13const MIN_UNIT_WIDTH: usize = 3;14const MIN_CHANGE_WIDTH: usize = 14;15// Leave room for long metric labels and comparison factors in the full layout.16const COMPACT_WIDTH_THRESHOLD: u16 = 110;1718/// Print a completed benchmark immediately, comparing every metric with benchmark 1.19pub fn print(20 number: usize,21 name: &str,22 measurements: &Measurements,23 metrics: &[MetricSelection],24 skip_unavailable_metrics: bool,25 reference: Option<&BenchmarkResult>,26) -> Result<()> {27 // Only adapt interactive output; redirected reports keep their usual layout.28 let compact = io::stdout().is_terminal()29 && terminal_size::terminal_size()30 .is_some_and(|(terminal_size::Width(width), _)| width < COMPACT_WIDTH_THRESHOLD);31 let comparison = reference.is_some();32 let multiple_runs = measurements.len() > 1;33 let value_columns = 1..if multiple_runs { 5 } else { 2 };34 let mut header = vec![35 String::new(),36 "mean".to_owned(),37 "σ".to_owned(),38 "min".to_owned(),39 "max".to_owned(),40 ];41 if !multiple_runs {42 header.truncate(2);43 header[1] = "Value".to_owned();44 }45 if comparison {46 header.extend([String::new(), String::new()]);47 }48 let mut rows = vec![(header, "")];49 for selection in metrics {50 let Some(summary) = selection.metric.summarize(measurements) else {51 ensure!(52 skip_unavailable_metrics,53 "Metric '{}' is unavailable for '{name}'",54 selection.metric.name()55 );56 continue;57 };58 let baseline = reference.and_then(|r| selection.metric.summarize(&r.measurements));59 // Keep auto units consistent with the first command for easier comparison.60 let scale_mean = baseline61 .as_ref()62 .filter(|stats| stats.mean != 0.0)63 .unwrap_or(&summary)64 .mean;65 let unit = selection.display_unit(scale_mean);66 let label = if compact && unit.symbol != "count" {67 format!("{} [{}]", selection.metric.label(), unit.symbol)68 } else {69 selection.metric.label().to_owned()70 };71 let mut row = vec![label, unit.format_value(summary.mean)];72 if let Some(stddev) = summary.stddev {73 row.push(unit.format_value(stddev));74 row.push(unit.format_value(summary.min));75 row.push(unit.format_value(summary.max));76 }77 if comparison {78 row.push(baseline.as_ref().map_or_else(79 || "N/A".to_owned(),80 |baseline| summary.format_change_from(baseline),81 ));82 row.push(baseline.as_ref().map_or_else(String::new, |baseline| {83 summary.format_factor_from(baseline, selection.metric)84 }));85 }86 rows.push((87 row,88 if unit.symbol == "count" {89 ""90 } else {91 unit.symbol92 },93 ));94 }95 // Align numbers and unit suffixes independently so mixed units do not shift96 // the values or the ± and … separators.97 let unit_width = rows98 .iter()99 .map(|(_, unit)| unit.chars().count())100 .max()101 .unwrap()102 .max(MIN_UNIT_WIDTH);103 // Keep labels aligned across benchmarks even when some metrics are skipped.104 let metric_width = metrics105 .iter()106 .map(|selection| selection.metric.label().chars().count())107 .max()108 .unwrap_or(0);109 let widths: Vec<_> = (0..rows[0].0.len())110 .map(|column| {111 let width = rows112 .iter()113 .map(|(row, _)| row[column].chars().count())114 .max()115 .unwrap();116 if column == 0 {117 width.max(metric_width)118 } else if value_columns.contains(&column) {119 width.max(if compact { 5 } else { MIN_VALUE_WIDTH })120 } else {121 width.max(if compact { 7 } else { MIN_CHANGE_WIDTH })122 }123 })124 .collect();125 let mut stdout = io::stdout().lock();126 console_writeln!(127 stdout,128 "{}: {} {}",129 format!("Benchmark {}", number + 1).bold(),130 name.white().bold(),131 format!(132 "({} {})",133 measurements.len(),134 if measurements.len() == 1 {135 "run"136 } else {137 "runs"138 }139 )140 .dimmed()141 )?;142 for (index, (row, unit)) in rows.iter().enumerate() {143 let mut line = String::new();144 for (column, value) in row.iter().enumerate() {145 let is_factor = comparison && column == row.len() - 1;146 let is_change = comparison && column >= row.len() - 2;147 if index == 0 && is_change {148 break;149 }150 if column > 0 {151 line.push_str(match (multiple_runs, column) {152 (true, 2) => " ± ",153 (true, 4) => " … ",154 _ => " ",155 });156 }157 let padding = " ".repeat(widths[column] - value.chars().count());158 let has_unit = !compact && value_columns.contains(&column);159 let text = if has_unit && !unit.is_empty() {160 format!("{value} {unit}")161 } else {162 value.clone()163 };164 let styled = if is_change {165 if row[row.len() - 2].starts_with('-') {166 text.green().to_string()167 } else if row[row.len() - 2].starts_with('+') {168 text.red().to_string()169 } else {170 text.normal().to_string()171 }172 } else if column == 1 || column == 2 {173 text.green().to_string()174 } else if column == 3 {175 text.cyan().to_string()176 } else if column == 4 {177 text.purple().to_string()178 } else {179 text.normal().to_string()180 };181 if column == 0 || is_factor {182 line.push_str(&format!("{styled}{padding}"));183 } else {184 line.push_str(&format!("{padding}{styled}"));185 }186 if has_unit && unit_width > 0 {187 // Empty suffixes (headers and unscaled counters) also need the188 // space normally separating a number from its unit.189 let unit_padding = unit_width - unit.chars().count() + usize::from(unit.is_empty());190 line.push_str(&" ".repeat(unit_padding));191 }192 }193 let line = line.trim_end();194 console_writeln!(195 stdout,196 " {}",197 if index == 1 {198 line.bold()199 } else {200 line.normal()201 }202 )?;203 }204 Ok(())205}