Use parameterized benchmarks as references
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Peter · committed by David Peter · parent 5d501b6 · Browse files · 13 files·+856 added−71 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+856 added−71 removed
- tests:+477 added−42 removed
- other:+379 added−29 removed
Provenance
- Commit
f7429e2- Tree
86112a3- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
5d501b6
13 files changed+856 added−71 removed
modified:doc/hyperfine.1+6 added-2 removed
114 unmodified lines115 not every time as would happen with the \fB\-\-prepare\fR option.116 .HP117 \fB\-\-reference\fR \fICMD\fP118 .IP119-Benchmark \fICMD\fP as the reference for the relative comparison of results.120-If this option is not specified, the fastest command is used as the reference.119+Use \fICMD\fP as the reference for the relative comparison of results. Without120+parameters, benchmark \fICMD\fP as a separate reference command. If this option121+is not specified, the fastest command is used as the reference.122+With \fB\-\-parameter\-scan\fR or \fB\-\-parameter\-list\fR, select an existing123+benchmark by its exact printed name. The name must match exactly one benchmark.124 .HP125 \fB\-\-reference\-name\fR \fINAME\fP126 .IP127 Give a meaningful \fINAME\fP to the reference command.128 Requires \fB\-\-reference\fR.129+Cannot be used with parameterized benchmarks; use \fB\-\-command\-name\fR instead.130 .HP131 \fB\-p\fR, \fB\-\-prepare\fR \fICMD...\fP132 .IP133 Execute \fICMD\fP before each timing run. This is useful for clearing disk caches,274 unmodified linesmodified:src/benchmark/relative_speed.rs+77 added-5 removed
27 unmodified lines28 .min_by(|&l, &r| compare_mean_time(l, r))29 .expect("at least one benchmark result")30 }31 32-fn compute_relative_speeds<'a>(32+pub fn compute_relative_speeds<'a>(33 results: &'a [BenchmarkResult],34 reference: &'a BenchmarkResult,35 sort_order: SortOrder,36 ) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> {37 let mut results: Vec<_> = results38 .iter()39 .map(|result| {40- let is_reference = result == reference;40+ // Separate benchmarks can have identical names and measurements.41+ let is_reference = std::ptr::eq(result, reference);42 let relative_ordering = compare_mean_time(result, reference);43 43- if result.mean_wall_clock_time() == Time::zero() {44+ if result.mean_wall_clock_time() == Time::zero()45+ || reference.mean_wall_clock_time() == Time::zero()46+ {47 return BenchmarkResultWithRelativeSpeed {48 result,49 relative_speed: if is_reference { 1.0 } else { f64::INFINITY },50 relative_speed_stddev: None,15 unmodified lines66 let ratio_stddev = match (67 result.measurements.stddev(),68 reference.measurements.stddev(),69 ) {67- (Some(result_stddev), Some(fastest_stddev)) => Some(70+ (Some(result_stddev), Some(reference_stddev)) => Some(71 ratio72 * ((result_stddev / result.mean_wall_clock_time())73 .powi(uom::typenum::P2::new())71- + (fastest_stddev / reference.mean_wall_clock_time())74+ + (reference_stddev / reference.mean_wall_clock_time())75 .powi(uom::typenum::P2::new()))76 .sqrt(),77 ),78 _ => None,115 unmodified lines194 let annotated_results = compute_with_check(&results, SortOrder::Command);195 196 assert!(annotated_results.is_none());197 }198+199+#[test]200+fn reference_identity_distinguishes_equal_results() {201+ let results = vec![create_result("same", 1.0), create_result("same", 1.0)];202+ let entries = compute_relative_speeds(&results, &results[0], SortOrder::Command);203+204+ assert!(entries[0].is_reference);205+ assert!(!entries[1].is_reference);206+}207+208+#[test]209+fn reference_ratios_indicate_faster_and_slower_runs() {210+ use approx::assert_relative_eq;211+212+ let results = vec![213+ create_result("faster", 1.0),214+ create_result("reference", 2.0),215+ create_result("slower", 3.0),216+ ];217+ let entries = compute_relative_speeds(&results, &results[1], SortOrder::Command);218+219+ assert_relative_eq!(entries[0].relative_speed, 2.0);220+ assert_relative_eq!(entries[1].relative_speed, 1.0);221+ assert_relative_eq!(entries[2].relative_speed, 1.5);222+ assert!(!entries[0].is_reference);223+ assert!(entries[1].is_reference);224+ assert!(!entries[2].is_reference);225+}226+227+#[test]228+fn reference_ratios_handle_zero_times() {229+ let mut results = vec![create_result("reference", 2.0), create_result("zero", 0.0)];230+ for result in &mut results {231+ let measurement = result.measurements.measurements[0];232+ result.measurements.measurements.push(measurement);233+ }234+ let entries = compute_relative_speeds(&results, &results[0], SortOrder::Command);235+ assert_eq!(entries[1].relative_speed, f64::INFINITY);236+237+ let entries = compute_relative_speeds(&results, &results[1], SortOrder::Command);238+ assert_eq!(entries[0].relative_speed, f64::INFINITY);239+ assert_eq!(entries[0].relative_speed_stddev, None);240+ assert_eq!(entries[1].relative_speed, 1.0);241+}242+243+#[test]244+fn reference_ratio_propagates_uncertainty() {245+ use crate::benchmark::measurement::Measurement;246+ use crate::quantity::second;247+ use approx::assert_relative_eq;248+249+ let mut results = vec![250+ create_result("faster", 1.0),251+ create_result("reference", 3.0),252+ ];253+ for (result, times) in results.iter_mut().zip([[1.0, 2.0, 3.0], [3.0, 4.0, 5.0]]) {254+ result.measurements.measurements = times255+ .iter()256+ .copied()257+ .map(|seconds| Measurement {258+ time_wall_clock: Time::new::<second>(seconds),259+ ..Default::default()260+ })261+ .collect();262+ }263+ let entries = compute_relative_speeds(&results, &results[1], SortOrder::Command);264+ assert_relative_eq!(entries[0].relative_speed, 2.0);265+ assert_relative_eq!(entries[0].relative_speed_stddev.unwrap(), 1.118033988749895);266+}modified:src/benchmark/scheduler.rs+27 added-7 removed
42 unmodified lines43 let reference = self44 .options45 .reference_command46 .as_ref()47+ .filter(|_| !self.options.parameterized_mode)48 .map(|cmd| Command::new(self.options.reference_name.as_deref(), cmd));49 50 executor.calibrate()?;51 2 unmodified lines54 .push(Benchmark::new(number, cmd, self.options, &*executor).run()?);55 56 // We export results after each individual benchmark, because57 // we would risk losing them if a later benchmark fails.57- self.export_manager.write_results(&self.results, true)?;58+ self.export_manager59+ .write_results(&self.results, true, self.reference_index())?;60 }61 62 Ok(())63 }7 unmodified lines71 return Ok(());72 }73 74 let reference = self73- .options74- .reference_command75- .as_ref()76- .map(|_| &self.results[0])75+ .reference_index()76+ .map(|index| &self.results[index])77 .unwrap_or_else(|| relative_speed::fastest_of(&self.results));78 79 if let Some(annotated_results) = relative_speed::compute_with_check_from_reference(80 &self.results,48 unmodified lines129 SortOrder::Command => {130 console_writeln!(stdout, "{}", "Relative speed comparison".bold())?;131 132 for item in annotated_results {133+ let relationship = if self.reference_index().is_none() {134+ ""135+ } else if item.is_reference {136+ " (reference)"137+ } else {138+ match item.relative_ordering {139+ Ordering::Less => " (faster)",140+ Ordering::Equal => " (same speed)",141+ Ordering::Greater => " (slower)",142+ }143+ };144 console_writeln!(145 stdout,135- " {}{} {}",146+ " {}{} {}{}",147 format!("{:10.2}", item.relative_speed).bold().green(),148 if item.is_reference {149 " ".into()150 } else if let Some(stddev) = item.relative_speed_stddev {1 unmodified line152 } else {153 " ".into()154 },155 item.result.command_with_unused_parameters,156+ relationship,157 )?;158 }159 }160 }12 unmodified lines173 174 Ok(())175 }176 177+ fn reference_index(&self) -> Option<usize> {178+ self.options179+ .reference_command180+ .as_ref()181+ .map(|_| self.options.parameterized_reference_index.unwrap_or(0))182+ }183+184 pub fn final_export(&self) -> Result<()> {166- self.export_manager.write_results(&self.results, false)185+ self.export_manager186+ .write_results(&self.results, false, self.reference_index())187 }188 }189 190 #[cfg(test)]67 unmodified linesmodified:src/export/csv.rs+2 added-1 removed
16 unmodified lines17 &self,18 results: &[BenchmarkResult],19 _unit: Option<TimeUnit>,20 _sort_order: SortOrder,21+ _reference_index: Option<usize>,22 ) -> Result<Vec<u8>> {23 const CSV_UNIT: TimeUnit = TimeUnit::Second;24 const CSV_PRECISION: usize = 6;25 146 unmodified lines172 ];173 174 let actual = String::from_utf8(175 exporter175- .serialize(&results, Some(TimeUnit::Second), SortOrder::Command)176+ .serialize(&results, Some(TimeUnit::Second), SortOrder::Command, None)177 .unwrap(),178 )179 .unwrap();180 6 unmodified linesmodified:src/export/json.rs+1 added
20 unmodified lines21 &self,22 results: &[BenchmarkResult],23 _unit: Option<TimeUnit>,24 _sort_order: SortOrder,25+ _reference_index: Option<usize>,26 ) -> Result<Vec<u8>> {27 let mut output = to_vec_pretty(&HyperfineSummary { results });28 if let Ok(ref mut content) = output {29 content.push(b'\n');5 unmodified linesmodified:src/export/markup.rs+39 added-6 removed
1 use crate::benchmark::relative_speed::BenchmarkResultWithRelativeSpeed;2 use crate::benchmark::{benchmark_result::BenchmarkResult, relative_speed};3 use crate::options::SortOrder;4-use crate::quantity::{FormatQuantity, IsUnit, TimeUnit};4+use crate::quantity::{FormatQuantity, IsUnit, Time, TimeUnit, Zero};5 6 use super::Exporter;7 use anyhow::Result;8+use std::cmp::Ordering;9 10 pub enum Alignment {11 Left,12 Right,3 unmodified lines16 fn table_results(17 &self,18 entries: &[BenchmarkResultWithRelativeSpeed],19 unit: TimeUnit,20+ reference_pending: bool,21+ explicit_reference: bool,22 ) -> String {23 // prepare table header strings24 let notation = format!("[{}]", unit.short_name());25 34 unmodified lines60 "".into()61 };62 let min_str = measurement.measurements.min().format_value(unit);63 let max_str = measurement.measurements.max().format_value(unit);61- let rel_str = format!("{:.2}", entry.relative_speed);62- let rel_stddev_str = if entry.is_reference {64+ // The ratio of two zero times is undefined, even if they compare equal.65+ let relative_unavailable = reference_pending66+ || (explicit_reference67+ && !entry.is_reference68+ && entry.relative_ordering == Ordering::Equal69+ && measurement.mean_wall_clock_time() == Time::zero());70+ let rel_str = if relative_unavailable {71+ "N/A".to_string()72+ } else {73+ format!("{:.2}", entry.relative_speed)74+ };75+ let rel_stddev_str = if relative_unavailable || entry.is_reference {76 "".into()77 } else if let Some(stddev) = entry.relative_speed_stddev {78 format!(" ± {stddev:.2}")79 } else {80 "".into()81 };82+ let rel_direction = if relative_unavailable || !explicit_reference {83+ ""84+ } else if entry.is_reference {85+ " (reference)"86+ } else {87+ match entry.relative_ordering {88+ Ordering::Less => " (faster)",89+ Ordering::Greater => " (slower)",90+ Ordering::Equal => " (same speed)",91+ }92+ };93 94 // prepare table row entries95 table.push_str(&self.table_row(&[96 &self.command(&cmd_str),97 &format!("{mean_str}{stddev_str}"),98 &min_str,99 &max_str,76- &format!("{rel_str}{rel_stddev_str}"),100+ &format!("{rel_str}{rel_stddev_str}{rel_direction}"),101 ]))102 }103 104 // emit table footer format32 unmodified lines137 &self,138 results: &[BenchmarkResult],139 unit: Option<TimeUnit>,140 sort_order: SortOrder,141+ reference_index: Option<usize>,142 ) -> Result<Vec<u8>> {143 let unit = unit.unwrap_or_else(|| determine_unit_from_results(results));119- let entries = relative_speed::compute(results, sort_order);144+ // Do not report ratios against another benchmark while the selected145+ // reference is still pending in an intermediate export.146+ let reference_pending = reference_index.is_some_and(|i| i >= results.len());147+ let entries = if let Some(reference) = reference_index.and_then(|i| results.get(i)) {148+ relative_speed::compute_relative_speeds(results, reference, sort_order)149+ } else {150+ relative_speed::compute(results, sort_order)151+ };152 121- let table = self.table_results(&entries, unit);153+ let table =154+ self.table_results(&entries, unit, reference_pending, reference_index.is_some());155 Ok(table.as_bytes().to_vec())156 }157 }modified:src/export/mod.rs+10 added-2 removed
49 unmodified lines50 &self,51 results: &[BenchmarkResult],52 unit: Option<TimeUnit>,53 sort_order: SortOrder,54+ reference_index: Option<usize>,55 ) -> Result<Vec<u8>>;56 }57 58 pub enum ExportTarget {71 unmodified lines130 /// is the final call after all benchmarks have been finished. In the former case,131 /// results are written to all file targets (to always have them up to date, even132 /// if a benchmark fails). In the latter case, we only print to stdout targets (in133 /// order not to clutter the output of hyperfine with intermediate results).133- pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> {134+ /// `reference_index` refers to the complete benchmark sequence, so it can135+ /// point past `results` while that benchmark is still pending.136+ pub fn write_results(137+ &self,138+ results: &[BenchmarkResult],139+ intermediate: bool,140+ reference_index: Option<usize>,141+ ) -> Result<()> {142 for e in &self.exporters {143 let content = || {144 e.exporter137- .serialize(results, self.time_unit, self.sort_order)145+ .serialize(results, self.time_unit, self.sort_order, reference_index)146 };147 148 match e.target {149 ExportTarget::File(ref filename) => {27 unmodified linesmodified:src/export/tests.rs+166 added-1 removed
11 unmodified lines12 results: &[BenchmarkResult],13 unit: Option<TimeUnit>,14 sort_order: SortOrder,15 ) -> String {16+ get_output_with_reference::<E>(results, unit, sort_order, None)17+}18+19+fn get_output_with_reference<E: Exporter + Default>(20+ results: &[BenchmarkResult],21+ unit: Option<TimeUnit>,22+ sort_order: SortOrder,23+ reference_index: Option<usize>,24+) -> String {25 let exporter = E::default();17- String::from_utf8(exporter.serialize(results, unit, sort_order).unwrap()).unwrap()26+ String::from_utf8(27+ exporter28+ .serialize(results, unit, sort_order, reference_index)29+ .unwrap(),30+ )31+ .unwrap()32 }33 34+#[test]35+fn test_markup_exports_identify_explicit_reference_and_direction() {36+ let benchmark = |name: &str, seconds| {37+ let measurement = Measurement {38+ time_wall_clock: Time::new::<second>(seconds),39+ ..Measurement::default()40+ };41+ BenchmarkResult {42+ command: name.to_owned(),43+ command_with_unused_parameters: name.to_owned(),44+ measurements: Measurements::new(vec![measurement, measurement]),45+ ..BenchmarkResult::default()46+ }47+ };48+ let results = [49+ benchmark("faster", 1.0),50+ benchmark("reference", 2.0),51+ benchmark("equal", 2.0),52+ benchmark("slower", 3.0),53+ ];54+55+ for sort_order in [SortOrder::Command, SortOrder::MeanTime] {56+ let outputs = [57+ get_output_with_reference::<MarkdownExporter>(58+ &results,59+ Some(TimeUnit::Second),60+ sort_order,61+ Some(1),62+ ),63+ get_output_with_reference::<AsciidocExporter>(64+ &results,65+ Some(TimeUnit::Second),66+ sort_order,67+ Some(1),68+ ),69+ get_output_with_reference::<OrgmodeExporter>(70+ &results,71+ Some(TimeUnit::Second),72+ sort_order,73+ Some(1),74+ ),75+ ];76+ for output in outputs {77+ for expected in [78+ "2.00 ± 0.00 (faster)",79+ "1.00 (reference)",80+ "1.00 ± 0.00 (same speed)",81+ "1.50 ± 0.00 (slower)",82+ ] {83+ assert!(output.contains(expected), "{}", output);84+ }85+ }86+ }87+}88+89+#[test]90+fn test_markup_exports_leave_pending_reference_ratios_unavailable() {91+ let results = [BenchmarkResult {92+ command: "sleep 1".into(),93+ command_with_unused_parameters: "sleep 1".into(),94+ measurements: Measurements::new(vec![Measurement {95+ time_wall_clock: Time::new::<second>(1.0),96+ ..Measurement::default()97+ }]),98+ ..BenchmarkResult::default()99+ }];100+ for sort_order in [SortOrder::Command, SortOrder::MeanTime] {101+ let outputs = [102+ get_output_with_reference::<MarkdownExporter>(103+ &results,104+ Some(TimeUnit::Second),105+ sort_order,106+ Some(1),107+ ),108+ get_output_with_reference::<AsciidocExporter>(109+ &results,110+ Some(TimeUnit::Second),111+ sort_order,112+ Some(1),113+ ),114+ get_output_with_reference::<OrgmodeExporter>(115+ &results,116+ Some(TimeUnit::Second),117+ sort_order,118+ Some(1),119+ ),120+ ];121+ for output in outputs {122+ assert!(output.contains("N/A"), "{}", output);123+ assert!(!output.contains("(reference)"), "{}", output);124+ }125+ }126+}127+128+#[test]129+fn test_markup_exports_with_zero_reference() {130+ let benchmark = |name: &str, seconds| BenchmarkResult {131+ command: name.to_owned(),132+ command_with_unused_parameters: name.to_owned(),133+ measurements: Measurements::new(vec![Measurement {134+ time_wall_clock: Time::new::<second>(seconds),135+ ..Measurement::default()136+ }]),137+ ..BenchmarkResult::default()138+ };139+ let results = [140+ benchmark("other zero", 0.0),141+ benchmark("reference", 0.0),142+ benchmark("slower", 1.0),143+ ];144+ for sort_order in [SortOrder::Command, SortOrder::MeanTime] {145+ for reference in [Some(1), Some(3), None] {146+ let outputs = [147+ get_output_with_reference::<MarkdownExporter>(148+ &results,149+ Some(TimeUnit::Second),150+ sort_order,151+ reference,152+ ),153+ get_output_with_reference::<AsciidocExporter>(154+ &results,155+ Some(TimeUnit::Second),156+ sort_order,157+ reference,158+ ),159+ get_output_with_reference::<OrgmodeExporter>(160+ &results,161+ Some(TimeUnit::Second),162+ sort_order,163+ reference,164+ ),165+ ];166+ for output in outputs {167+ match reference {168+ Some(1) => {169+ assert_eq!(output.matches("N/A").count(), 1, "{}", output);170+ assert!(output.contains("1.00 (reference)"), "{}", output);171+ assert!(output.contains("inf (slower)"), "{}", output);172+ }173+ Some(_) => assert_eq!(output.matches("N/A").count(), 3, "{}", output),174+ None => {175+ assert!(!output.contains("N/A"), "{}", output);176+ assert!(output.contains("inf"), "{}", output);177+ assert!(!output.contains("(reference)"), "{}", output);178+ }179+ }180+ }181+ }182+ }183+}184+185 /// Ensure the makrup output includes the table header and the multiple186 /// benchmark results as a table. The list of actual times is not included187 /// in the output.188 ///402 unmodified linesmodified:src/cli.rs+7 added-3 removed
103 unmodified lines104 .long("reference")105 .action(ArgAction::Set)106 .value_name("CMD")107 .help(108- "The reference command for the relative comparison of results. \109- If this is unset, results are compared with the fastest command as reference."108+ "The reference for the relative comparison of results. Without parameters, \109+ CMD is run as a separate reference command. With --parameter-scan or \110+ --parameter-list, CMD must exactly match one unique benchmark name as \111+ shown in the output. If this is unset, results are compared with the \112+ fastest command as reference."113 )114 )115 .arg(116 Arg::new("reference-name")117 .long("reference-name")118 .action(ArgAction::Set)119 .value_name("CMD")117- .help("Give a meaningful name to the reference command.")120+ .help("Give a meaningful name to the reference command. This cannot be used \121+ with parameterized benchmarks; use --command-name instead.")122 .requires("reference")123 )124 .arg(125 Arg::new("prepare")311 unmodified linesmodified:src/options.rs+34 added-2 removed
2 unmodified lines3 use std::path::PathBuf;4 use std::process::{Command, Stdio};5 use std::{cmp, env, fmt, io};6 7-use anyhow::ensure;7+use anyhow::{bail, ensure};8 use clap::ArgMatches;9 10 use crate::command::Commands;11 use crate::error::OptionsError;201 unmodified lines213 214 // Name of the reference command215 pub reference_name: Option<String>,216 217+ // Whether commands are expanded from --parameter-scan or --parameter-list.218+ pub parameterized_mode: bool,219+220+ // Index of the selected command in a parameterized run, if any.221+ pub parameterized_reference_index: Option<usize>,222+223 /// Command(s) to run before each timing run224 pub preparation_command: Option<Vec<String>>,225 226 /// Command(s) to run after each timing run35 unmodified lines262 min_benchmarking_time: Time::new::<second>(3.0),263 command_failure_action: CmdFailureAction::RaiseError,264 reference_command: None,265 reference_name: None,266+ parameterized_mode: false,267+ parameterized_reference_index: None,268 preparation_command: None,269 conclusion_command: None,270 setup_command: None,271 cleanup_command: None,44 unmodified lines316 };317 318 options.setup_command = matches.get_one::<String>("setup").map(String::from);319 320+ options.parameterized_mode = matches.get_many::<String>("parameter-scan").is_some()321+ || matches.get_many::<String>("parameter-list").is_some();322 options.reference_command = matches.get_one::<String>("reference").map(String::from);323 options.reference_name = matches324 .get_one::<String>("reference-name")325 .map(String::from);147 unmodified lines473 Ok(options)474 }475 476 pub fn validate_against_command_list(&mut self, commands: &Commands) -> Result<()> {477+ if self.parameterized_mode {478+ if let Some(reference) = &self.reference_command {479+ ensure!(480+ self.reference_name.is_none(),481+ "--reference-name cannot be used with a parameterized reference; use --command-name to name the benchmark"482+ );483+ let mut matches = commands484+ .iter()485+ .enumerate()486+ .filter(|(_, command)| command.get_name_with_unused_parameters() == *reference);487+ let Some((index, _)) = matches.next() else {488+ bail!(489+ "Reference '{reference}' does not match any parameterized benchmark. Use its full displayed benchmark name."490+ );491+ };492+ ensure!(493+ matches.next().is_none(),494+ "Reference '{reference}' matches multiple parameterized benchmarks. Use --command-name to give them unique names."495+ );496+ self.parameterized_reference_index = Some(index);497+ }498+ }467- let has_reference_command = self.reference_command.is_some();499+ let has_reference_command = self.reference_command.is_some() && !self.parameterized_mode;500 let num_commands = commands.num_commands(has_reference_command);501 502 if let Some(preparation_command) = &self.preparation_command {503 ensure!(72 unmodified linesmodified:tests/execution_order_tests.rs+2 added-4 removed
382 unmodified lines383 .run();384 }385 386 #[test]387-fn reference_is_executed_first_parameter_value() {387+fn parameterized_reference_keeps_parameter_order() {388 ExecutionOrderTest::new()389 .arg("--runs=2")390- .reference("reference")390+ .reference("command 2")391 .arg("--parameter-list")392 .arg("number")393 .arg("1,2,3")394 .command("command {number}")395- .expect_output("reference")396- .expect_output("reference")395 .expect_output("command 1")396 .expect_output("command 1")397 .expect_output("command 2")398 .expect_output("command 2")163 unmodified linesmodified:tests/integration_tests.rs+475 added-38 removed
704 unmodified lines705 ");706 }707 708 #[test]709+fn command_sorted_comparison_labels_explicit_reference() {710+ for (args, expected) in [711+ (712+ vec!["--reference", "sleep 2", "sleep 1", "sleep 3"],713+ vec![714+ "1.00 sleep 2 (reference)",715+ "2.00 ± 0.00 sleep 1 (faster)",716+ "1.50 ± 0.00 sleep 3 (slower)",717+ ],718+ ),719+ (720+ vec!["--reference", "sleep 2", "sleep 2"],721+ vec![722+ "1.00 sleep 2 (reference)",723+ "1.00 ± 0.00 sleep 2 (same speed)",724+ ],725+ ),726+ ] {727+ let output = hyperfine_debug()728+ .args(["--style=basic", "--runs=2", "--sort=command"])729+ .args(args)730+ .output()731+ .unwrap();732+ assert!(output.status.success(), "{:?}", output);733+ let stdout = String::from_utf8(output.stdout).unwrap();734+ let comparison = stdout.split_once("Relative speed comparison\n").unwrap().1;735+ assert_eq!(736+ comparison.lines().map(str::trim).collect::<Vec<_>>(),737+ expected738+ );739+ }740+}741+742+#[test]743 fn shows_reference_name() {744 let _settings = snapshot_settings().bind_to_scope();745 assert_cmd_snapshot!(hyperfine_debug()746 .arg("--style=basic")82 unmodified lines829 }830 }831 832 #[test]799-fn performs_reference_and_all_benchmarks_in_parameter_scan() {800- let _settings = snapshot_settings().bind_to_scope();801- assert_cmd_snapshot!(hyperfine_debug()802- .arg("--style=basic")803- .arg("--reference=sleep 25")804- .arg("--parameter-scan")805- .arg("time")806- .arg("30")807- .arg("45")808- .arg("--parameter-step-size")809- .arg("5")810- .arg("sleep {time}"), @r"811- success: true812- exit_code: 0813- ----- stdout -----814- Benchmark 1: sleep 25815- Time (mean ± σ): 25.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]816- Range (min … max): 25.000 s … 25.000 s 10 runs833+fn selects_reference_from_parameter_scan() {834+ let output = hyperfine_debug()835+ .args([836+ "--style=basic",837+ "--reference=sleep 35",838+ "--parameter-scan",839+ "time",840+ "30",841+ "45",842+ "--parameter-step-size",843+ "5",844+ "sleep {time}",845+ ])846+ .output()847+ .unwrap();848+ assert!(output.status.success(), "{:?}", output);849+ let stdout = String::from_utf8(output.stdout).unwrap();850+ let benchmarks: Vec<_> = stdout851+ .lines()852+ .filter(|line| line.starts_with("Benchmark "))853+ .collect();854+ assert_eq!(855+ benchmarks,856+ [857+ "Benchmark 1: sleep 30",858+ "Benchmark 2: sleep 35",859+ "Benchmark 3: sleep 40",860+ "Benchmark 4: sleep 45",861+ ]862+ );863+ assert!(stdout.contains("Summary\n sleep 35 ran\n"), "{}", stdout);864+}865 818- Benchmark 2: sleep 30819- Time (mean ± σ): 30.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]820- Range (min … max): 30.000 s … 30.000 s 10 runs866+#[cfg(unix)]867+#[test]868+fn selects_reference_with_parameterized_prepare() {869+ let directory = tempfile::tempdir().unwrap();870+ let csv_path = directory.path().join("results.csv");871+ let json_path = directory.path().join("results.json");872+ let output = hyperfine_raw_command()873+ .args([874+ "--style=basic",875+ "--shell=none",876+ "--runs=1",877+ "-L",878+ "delay",879+ "0.2,0.4,0.6",880+ "--prepare",881+ "sleep {delay}",882+ "--reference",883+ "echo a (delay = 0.4)",884+ "--export-csv",885+ ])886+ .arg(&csv_path)887+ .arg("--export-json")888+ .arg(&json_path)889+ .arg("echo a")890+ .output()891+ .unwrap();892+ assert!(output.status.success(), "{:?}", output);893+ let stdout = String::from_utf8(output.stdout).unwrap();894+ assert_eq!(stdout.matches("Benchmark ").count(), 3);895+ assert!(stdout.contains("echo a (delay = 0.4) ran"), "{}", stdout);896 822- Benchmark 3: sleep 35823- Time (mean ± σ): 35.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]824- Range (min … max): 35.000 s … 35.000 s 10 runs897+ let mut csv = csv::Reader::from_path(csv_path).unwrap();898+ assert!(csv899+ .headers()900+ .unwrap()901+ .iter()902+ .any(|header| header == "parameter_delay"));903+ let records: Vec<_> = csv.records().map(|record| record.unwrap()).collect();904+ assert_eq!(records.len(), 3);905+ let json: serde_json::Value =906+ serde_json::from_slice(&std::fs::read(json_path).unwrap()).unwrap();907+ let results = json["results"].as_array().unwrap();908+ assert_eq!(results.len(), 3);909+ assert_eq!(910+ results911+ .iter()912+ .map(|result| result["parameters"]["delay"].as_str().unwrap())913+ .collect::<Vec<_>>(),914+ ["0.2", "0.4", "0.6"]915+ );916+}917 826- Benchmark 4: sleep 40827- Time (mean ± σ): 40.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]828- Range (min … max): 40.000 s … 40.000 s 10 runs918+#[test]919+fn selects_reference_by_custom_benchmark_name() {920+ for (command, name, reference) in [921+ ("sleep {x}", "case-{x}", "case-2"),922+ ("sleep 1", "case-{x}", "case-2 (x = 2)"),923+ ] {924+ let output = hyperfine_debug()925+ .args([926+ "--style=basic",927+ "--runs=1",928+ "-L",929+ "x",930+ "1,2",931+ "--command-name",932+ name,933+ "--reference",934+ reference,935+ command,936+ ])937+ .output()938+ .unwrap();939+ assert!(output.status.success(), "{:?}", output);940+ let stdout = String::from_utf8(output.stdout).unwrap();941+ assert_eq!(stdout.matches("Benchmark ").count(), 2);942+ assert!(stdout.contains(&format!("{reference} ran")), "{}", stdout);943+ }944+}945 830- Benchmark 5: sleep 45831- Time (mean ± σ): 45.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]832- Range (min … max): 45.000 s … 45.000 s 10 runs946+#[test]947+fn selects_reference_from_multiple_commands_and_parameters() {948+ let output = hyperfine_debug()949+ .args([950+ "--style=basic",951+ "--runs=1",952+ "-L",953+ "x",954+ "1,2",955+ "-L",956+ "y",957+ "3,4",958+ "--reference",959+ "sleep 4 (x = 2)",960+ "sleep {x}",961+ "sleep {y}",962+ ])963+ .output()964+ .unwrap();965+ assert!(output.status.success(), "{:?}", output);966+ let stdout = String::from_utf8(output.stdout).unwrap();967+ assert_eq!(stdout.matches("Benchmark ").count(), 8);968+ assert!(stdout.contains("sleep 4 (x = 2) ran"), "{}", stdout);969+}970 834- Summary835- sleep 25 ran836- 1.20 ± 0.00 times faster than sleep 30837- 1.40 ± 0.00 times faster than sleep 35838- 1.60 ± 0.00 times faster than sleep 40839- 1.80 ± 0.00 times faster than sleep 45971+#[test]972+fn rejects_unmatched_parameterized_reference_before_creating_export() {973+ let directory = tempfile::tempdir().unwrap();974+ let export_path = directory.path().join("results.csv");975+ let marker_path = directory.path().join("setup-ran");976+ for (args, benchmark) in [977+ (vec!["-L", "x", "1,2", "--reference", "echo 3"], "echo {x}"),978+ (979+ vec!["--reference", "sleep 1", "-P", "secs", "2", "3"],980+ "sleep {secs}",981+ ),982+ ] {983+ std::fs::write(&export_path, "previous contents").unwrap();984+ hyperfine()985+ .args(args)986+ .arg("--setup")987+ .arg(format!("echo touched > \"{}\"", marker_path.display()))988+ .arg("--export-csv")989+ .arg(&export_path)990+ .arg(benchmark)991+ .assert()992+ .failure()993+ .stdout(predicate::str::is_empty())994+ .stderr(predicate::str::contains(995+ "does not match any parameterized benchmark",996+ ));997 841- ----- stderr -----842- ");998+ assert_eq!(999+ std::fs::read_to_string(&export_path).unwrap(),1000+ "previous contents"1001+ );1002+ assert!(!marker_path.exists());1003+ }1004 }1005 1006 #[test]1007+fn rejects_ambiguous_parameterized_reference() {1008+ for args in [1009+ vec![1010+ "-L",1011+ "x",1012+ "1,2",1013+ "--command-name",1014+ "case",1015+ "--reference",1016+ "case",1017+ "sleep {x}",1018+ ],1019+ vec!["-L", "x", "1,1", "--reference", "sleep 1", "sleep {x}"],1020+ ] {1021+ hyperfine_debug()1022+ .args(args)1023+ .assert()1024+ .failure()1025+ .stdout(predicate::str::is_empty())1026+ .stderr(predicate::str::contains(1027+ "matches multiple parameterized benchmarks",1028+ ));1029+ }1030+}1031+1032+#[test]1033+fn rejects_reference_name_with_parameterized_reference() {1034+ hyperfine_debug()1035+ .args([1036+ "-L",1037+ "x",1038+ "1,2",1039+ "--reference",1040+ "sleep 1",1041+ "--reference-name",1042+ "baseline",1043+ "sleep {x}",1044+ ])1045+ .assert()1046+ .failure()1047+ .stderr(predicate::str::contains(1048+ "--reference-name cannot be used with a parameterized reference",1049+ ));1050+}1051+1052+#[test]1053+fn parameterized_reference_preserves_per_benchmark_hook_order() {1054+ let directory = tempfile::tempdir().unwrap();1055+ let log_path = directory.path().join("hooks.log");1056+ let prepare = |name: &str| format!("echo {name} >> \"{}\"", log_path.display());1057+ let command = format!("echo benchmark-{{x}} >> \"{}\"", log_path.display());1058+1059+ hyperfine()1060+ .args(["--runs=1", "-L", "x", "1,2,3"])1061+ .arg("--command-name")1062+ .arg("case-{x}")1063+ .arg("--reference")1064+ .arg("case-2")1065+ .arg("--prepare")1066+ .arg(prepare("prepare-1"))1067+ .arg("--prepare")1068+ .arg(prepare("prepare-2"))1069+ .arg("--prepare")1070+ .arg(prepare("prepare-3"))1071+ .arg(command)1072+ .assert()1073+ .success();1074+1075+ let contents = std::fs::read_to_string(log_path).unwrap();1076+ assert_eq!(1077+ contents.lines().map(str::trim).collect::<Vec<_>>(),1078+ [1079+ "prepare-1",1080+ "benchmark-1",1081+ "prepare-2",1082+ "benchmark-2",1083+ "prepare-3",1084+ "benchmark-3"1085+ ]1086+ );1087+}1088+1089+#[test]1090+fn parameterized_reference_preserves_per_benchmark_output_order() {1091+ let directory = tempfile::tempdir().unwrap();1092+ let output_paths = [1093+ directory.path().join("one.txt"),1094+ directory.path().join("two.txt"),1095+ directory.path().join("three.txt"),1096+ ];1097+ let mut command = hyperfine();1098+ command.args([1099+ "--runs=1",1100+ "-L",1101+ "x",1102+ "1,2,3",1103+ "--command-name",1104+ "case-{x}",1105+ "--reference",1106+ "case-2",1107+ ]);1108+ for path in &output_paths {1109+ command.arg("--output").arg(path);1110+ }1111+ command.arg("echo benchmark-{x}").assert().success();1112+1113+ for (path, expected) in output_paths1114+ .iter()1115+ .zip(["benchmark-1", "benchmark-2", "benchmark-3"])1116+ {1117+ assert_eq!(std::fs::read_to_string(path).unwrap().trim(), expected);1118+ }1119+}1120+1121+#[cfg(unix)]1122+#[test]1123+fn intermediate_markdown_waits_for_selected_reference() {1124+ let directory = tempfile::tempdir().unwrap();1125+ for (reference, preparations, reference_available) in [1126+ ("sleep 0.03", ["true", "false", "true"], false),1127+ ("sleep 0.02", ["true", "true", "false"], true),1128+ ] {1129+ let export_path = directory.path().join("results.md");1130+ let mut command = hyperfine();1131+ command.args([1132+ "--style=none",1133+ "--shell=none",1134+ "--runs=1",1135+ "-L",1136+ "delay",1137+ "0.01,0.02,0.03",1138+ "--reference",1139+ reference,1140+ ]);1141+ for preparation in preparations {1142+ command.arg("--prepare").arg(preparation);1143+ }1144+ command1145+ .arg("--export-markdown")1146+ .arg(&export_path)1147+ .arg("sleep {delay}")1148+ .assert()1149+ .failure()1150+ .stderr(predicate::str::contains(1151+ "The preparation command terminated",1152+ ));1153+ let markdown = std::fs::read_to_string(&export_path).unwrap();1154+ if reference_available {1155+ assert!(!markdown.contains("N/A"), "{}", markdown);1156+ let row = markdown1157+ .lines()1158+ .find(|line| line.contains("sleep 0.02"))1159+ .unwrap();1160+ assert!(row.ends_with("| 1.00 (reference) |"), "{}", row);1161+ } else {1162+ let row = markdown1163+ .lines()1164+ .find(|line| line.contains("sleep 0.01"))1165+ .unwrap();1166+ assert!(row.ends_with("| N/A |"), "{}", row);1167+ }1168+ }1169+}1170+1171+#[test]1172+fn markdown_export_uses_selected_parameterized_reference() {1173+ for sort_order in ["command", "mean-time"] {1174+ let output = hyperfine_debug()1175+ .args([1176+ "--style=none",1177+ "--runs=1",1178+ "--time-unit=second",1179+ "--export-markdown=-",1180+ "--sort",1181+ sort_order,1182+ "-L",1183+ "x",1184+ "3,2,1",1185+ "--reference",1186+ "sleep 2",1187+ "sleep {x}",1188+ ])1189+ .output()1190+ .unwrap();1191+ assert!(output.status.success(), "{:?}", output);1192+ let stdout = String::from_utf8(output.stdout).unwrap();1193+ let rows: Vec<_> = stdout1194+ .lines()1195+ .filter(|line| line.contains("sleep "))1196+ .collect();1197+ if sort_order == "command" {1198+ assert!(rows[0].contains("sleep 3"));1199+ assert!(rows[1].contains("sleep 2"));1200+ assert!(rows[2].contains("sleep 1"));1201+ } else {1202+ assert!(rows[0].contains("sleep 1"));1203+ assert!(rows[1].contains("sleep 2"));1204+ assert!(rows[2].contains("sleep 3"));1205+ }1206+ for (command, relative) in [1207+ ("sleep 1", "2.00 (faster)"),1208+ ("sleep 2", "1.00 (reference)"),1209+ ("sleep 3", "1.50 (slower)"),1210+ ] {1211+ let row = rows.iter().find(|line| line.contains(command)).unwrap();1212+ assert!(row.ends_with(&format!("| {relative} |")), "{}", row);1213+ }1214+ }1215+}1216+1217+#[test]1218+fn markdown_export_uses_standalone_reference() {1219+ for sort_order in ["command", "mean-time"] {1220+ let output = hyperfine_debug()1221+ .args([1222+ "--style=none",1223+ "--runs=1",1224+ "--time-unit=second",1225+ "--export-markdown=-",1226+ "--sort",1227+ sort_order,1228+ "--reference",1229+ "sleep 2",1230+ "--reference-name",1231+ "baseline",1232+ "sleep 1",1233+ "sleep 2",1234+ "sleep 3",1235+ ])1236+ .output()1237+ .unwrap();1238+ assert!(output.status.success(), "{:?}", output);1239+ let stdout = String::from_utf8(output.stdout).unwrap();1240+ for (command, relative) in [1241+ ("baseline", "1.00 (reference)"),1242+ ("sleep 1", "2.00 (faster)"),1243+ ("sleep 2", "1.00 (same speed)"),1244+ ("sleep 3", "1.50 (slower)"),1245+ ] {1246+ let row = stdout.lines().find(|line| line.contains(command)).unwrap();1247+ assert!(row.ends_with(&format!("| {relative} |")), "{}", row);1248+ }1249+ }1250+}1251+1252+#[test]1253+fn markdown_export_without_explicit_reference_is_unchanged() {1254+ for sort_order in ["command", "mean-time"] {1255+ let output = hyperfine_debug()1256+ .args([1257+ "--style=none",1258+ "--runs=1",1259+ "--time-unit=second",1260+ "--export-markdown=-",1261+ "--sort",1262+ sort_order,1263+ "sleep 3",1264+ "sleep 1",1265+ "sleep 2",1266+ ])1267+ .output()1268+ .unwrap();1269+ assert!(output.status.success(), "{:?}", output);1270+ let stdout = String::from_utf8(output.stdout).unwrap();1271+ for (command, relative) in [1272+ ("sleep 1", "1.00"),1273+ ("sleep 2", "2.00"),1274+ ("sleep 3", "3.00"),1275+ ] {1276+ let row = stdout.lines().find(|line| line.contains(command)).unwrap();1277+ assert!(row.ends_with(&format!("| {relative} |")), "{}", row);1278+ }1279+ }1280+}1281+1282+#[test]1283 fn intermediate_results_are_not_exported_to_stdout() {1284 let _settings = snapshot_settings().bind_to_scope();1285 assert_cmd_snapshot!(hyperfine_debug()1286 .arg("--style=none") // To only see the Markdown export on stdout232 unmodified linesmodified:README.md+10 added
96 unmodified lines97 --setup 'git switch {branch}' \98 'python main.py'99 ```100 101+To compare a parameterized benchmark against a particular run, pass its exact printed name to102+`--reference`. For example:103+```sh104+hyperfine -L delay 0.2,0.4,0.6 --prepare 'sleep {delay}' --reference 'echo a (delay = 0.4)' 'echo a'105+```106+The name must identify exactly one benchmark, including any `--command-name` and displayed unused107+parameters. `--reference-name` cannot be used with parameterized benchmarks; use `--command-name`108+to name them instead. Without `--parameter-scan` or `--parameter-list`, `--reference` runs a109+separate reference command.110+111 If you need a unique value for each individual run of a benchmark command, hyperfine also exposes112 the zero-based `$HYPERFINE_ITERATION` environment variable inside the benchmarked command itself:113 ```sh114 hyperfine 'my-command > output-${HYPERFINE_ITERATION}.log'250 unmodified lines