Simplify parameterized reference handling
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 f7429e2 · Browse files · 8 files·+209 added−692 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+209 added−692 removed
- tests:+147 added−404 removed
- other:+62 added−288 removed
Provenance
- Commit
463a889- Tree
7ec0960- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
f7429e2
8 files changed+209 added−692 removed
modified:src/benchmark/relative_speed.rs+22 added-52 removed
14 unmodified lines15 // Less means faster16 pub relative_ordering: Ordering,17 }18 19+impl BenchmarkResultWithRelativeSpeed<'_> {20+ pub fn reference_label(&self) -> &'static str {21+ if self.is_reference {22+ " (reference)"23+ } else {24+ match self.relative_ordering {25+ Ordering::Less => " (faster)",26+ Ordering::Equal => " (same speed)",27+ Ordering::Greater => " (slower)",28+ }29+ }30+ }31+}32+33 pub fn compare_mean_time(l: &BenchmarkResult, r: &BenchmarkResult) -> Ordering {34 l.mean_wall_clock_time()35 .partial_cmp(&r.mean_wall_clock_time())36 .unwrap_or(Ordering::Equal)5 unmodified lines42 .min_by(|&l, &r| compare_mean_time(l, r))43 .expect("at least one benchmark result")44 }45 32-pub fn compute_relative_speeds<'a>(46+fn compute_relative_speeds<'a>(47 results: &'a [BenchmarkResult],48 reference: &'a BenchmarkResult,49 sort_order: SortOrder,50 ) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> {87 unmodified lines138 139 Some(compute_relative_speeds(results, fastest, sort_order))140 }141 128-/// Same as compute_with_check, potentially resulting in relative speeds of infinity129-pub fn compute(130- results: &[BenchmarkResult],142+/// Compute relative speeds against the given reference, or the fastest result.143+pub fn compute<'a>(144+ results: &'a [BenchmarkResult],145 sort_order: SortOrder,132-) -> Vec<BenchmarkResultWithRelativeSpeed<'_>> {133- let fastest = fastest_of(results);134-135- compute_relative_speeds(results, fastest, sort_order)146+ reference: Option<&'a BenchmarkResult>,147+) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> {148+ let reference = reference.unwrap_or_else(|| fastest_of(results));149+ compute_relative_speeds(results, reference, sort_order)150 }151 152 #[cfg(test)]153 fn create_result(name: &str, mean: f64) -> BenchmarkResult {65 unmodified lines219 assert!(!entries[1].is_reference);220 }221 222 #[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]223 fn reference_ratios_handle_zero_times() {224 let mut results = vec![create_result("reference", 2.0), create_result("zero", 0.0)];225 for result in &mut results {226 let measurement = result.measurements.measurements[0];6 unmodified lines233 assert_eq!(entries[0].relative_speed, f64::INFINITY);234 assert_eq!(entries[0].relative_speed_stddev, None);235 assert_eq!(entries[1].relative_speed, 1.0);236 }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+7 added-20 removed
42 unmodified lines43 let reference = self44 .options45 .reference_command46 .as_ref()47- .filter(|_| !self.options.parameterized_mode)47 .map(|cmd| Command::new(self.options.reference_name.as_deref(), cmd));48 49 executor.calibrate()?;50 3 unmodified lines54 55 // We export results after each individual benchmark, because56 // we would risk losing them if a later benchmark fails.57 self.export_manager59- .write_results(&self.results, true, self.reference_index())?;58+ .write_results(&self.results, true, self.options.reference_index)?;59 }60 61 Ok(())62 }7 unmodified lines70 return Ok(());71 }72 73 let reference = self74+ .options75- .reference_index()75+ .reference_index76 .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(49 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)"133+ let relationship = if self.options.reference_index.is_some() {134+ item.reference_label()135 } else {138- match item.relative_ordering {139- Ordering::Less => " (faster)",140- Ordering::Equal => " (same speed)",141- Ordering::Greater => " (slower)",142- }136+ ""137 };138 console_writeln!(139 stdout,140 " {}{} {}{}",26 unmodified lines167 168 Ok(())169 }170 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-171 pub fn final_export(&self) -> Result<()> {172 self.export_manager186- .write_results(&self.results, false, self.reference_index())173+ .write_results(&self.results, false, self.options.reference_index)174 }175 }176 177 #[cfg(test)]67 unmodified linesmodified:src/export/markup.rs+17 added-26 removed
65 unmodified lines66 || (explicit_reference67 && !entry.is_reference68 && entry.relative_ordering == Ordering::Equal69 && measurement.mean_wall_clock_time() == Time::zero());70- let rel_str = if relative_unavailable {70+ let relative = if relative_unavailable {71 "N/A".to_string()72 } else {73+ let stddev = match (entry.is_reference, entry.relative_speed_stddev) {74+ (false, Some(stddev)) => format!(" ± {stddev:.2}"),75+ _ => String::new(),76+ };77+ let label = if explicit_reference {78+ entry.reference_label()79+ } else {80+ ""81+ };73- format!("{:.2}", entry.relative_speed)82+ format!("{:.2}{stddev}{label}", entry.relative_speed)83 };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- };84 85 // prepare table row entries86 table.push_str(&self.table_row(&[87 &self.command(&cmd_str),88 &format!("{mean_str}{stddev_str}"),89 &min_str,90 &max_str,100- &format!("{rel_str}{rel_stddev_str}{rel_direction}"),91+ &relative,92 ]))93 }94 95 // emit table footer format38 unmodified lines134 let unit = unit.unwrap_or_else(|| determine_unit_from_results(results));135 // Do not report ratios against another benchmark while the selected136 // reference is still pending in an intermediate export.137 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- };138+ let entries = relative_speed::compute(139+ results,140+ sort_order,141+ reference_index.and_then(|i| results.get(i)),142+ );143 144 let table =145 self.table_results(&entries, unit, reference_pending, reference_index.is_some());146 Ok(table.as_bytes().to_vec())2 unmodified linesmodified:src/export/tests.rs+1 added-166 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 {16 let exporter = E::default();26- String::from_utf8(27- exporter28- .serialize(results, unit, sort_order, reference_index)29- .unwrap(),30- )31- .unwrap()17+ String::from_utf8(exporter.serialize(results, unit, sort_order, None).unwrap()).unwrap()18 }19 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-20 /// Ensure the makrup output includes the table header and the multiple21 /// benchmark results as a table. The list of actual times is not included22 /// in the output.23 ///402 unmodified linesmodified:src/options.rs+15 added-14 removed
206 unmodified lines207 208 /// Whether or not to ignore non-zero exit codes209 pub command_failure_action: CmdFailureAction,210 211- // Command to use as a reference for relative speed comparison211+ // Standalone reference command, cleared when an existing benchmark is selected.212 pub reference_command: Option<String>,213 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,217+ // Index of the reference in the benchmark sequence, if any.218+ pub reference_index: Option<usize>,219 220- // Index of the selected command in a parameterized run, if any.221- pub parameterized_reference_index: Option<usize>,222-220 /// Command(s) to run before each timing run221 pub preparation_command: Option<Vec<String>>,222 223 /// Command(s) to run after each timing run35 unmodified lines259 min_benchmarking_time: Time::new::<second>(3.0),260 command_failure_action: CmdFailureAction::RaiseError,261 reference_command: None,262 reference_name: None,266- parameterized_mode: false,267- parameterized_reference_index: None,263+ reference_index: None,264 preparation_command: None,265 conclusion_command: None,266 setup_command: None,267 cleanup_command: None,44 unmodified lines312 };313 314 options.setup_command = matches.get_one::<String>("setup").map(String::from);315 320- options.parameterized_mode = matches.get_many::<String>("parameter-scan").is_some()321- || matches.get_many::<String>("parameter-list").is_some();316 options.reference_command = matches.get_one::<String>("reference").map(String::from);317 options.reference_name = matches318 .get_one::<String>("reference-name")319 .map(String::from);147 unmodified lines467 Ok(options)468 }469 470 pub fn validate_against_command_list(&mut self, commands: &Commands) -> Result<()> {477- if self.parameterized_mode {478- if let Some(reference) = &self.reference_command {471+ if let Some(reference) = &self.reference_command {472+ if commands473+ .iter()474+ .next()475+ .is_some_and(|command| !command.get_parameters().is_empty())476+ {477 ensure!(478 self.reference_name.is_none(),479 "--reference-name cannot be used with a parameterized reference; use --command-name to name the benchmark"480 );9 unmodified lines490 ensure!(491 matches.next().is_none(),492 "Reference '{reference}' matches multiple parameterized benchmarks. Use --command-name to give them unique names."493 );496- self.parameterized_reference_index = Some(index);494+ self.reference_index = Some(index);495+ self.reference_command = None;496+ } else {497+ self.reference_index = Some(0);498 }499 }499- let has_reference_command = self.reference_command.is_some() && !self.parameterized_mode;500+ let has_reference_command = self.reference_command.is_some();501 let num_commands = commands.num_commands(has_reference_command);502 503 if let Some(preparation_command) = &self.preparation_command {504 ensure!(72 unmodified linesmodified:tests/execution_order_tests.rs-18 removed
382 unmodified lines383 .run();384 }385 386 #[test]387-fn parameterized_reference_keeps_parameter_order() {388- ExecutionOrderTest::new()389- .arg("--runs=2")390- .reference("command 2")391- .arg("--parameter-list")392- .arg("number")393- .arg("1,2,3")394- .command("command {number}")395- .expect_output("command 1")396- .expect_output("command 1")397- .expect_output("command 2")398- .expect_output("command 2")399- .expect_output("command 3")400- .expect_output("command 3")401- .run();402-}403-404-#[test]387 fn reference_is_executed_separately_from_commands() {388 ExecutionOrderTest::new()389 .arg("--runs=1")390 .reference("command 1")153 unmodified linesmodified:tests/integration_tests.rs+147 added-386 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- ),709+fn command_sorted_comparison_and_markup_identify_reference() {710+ let directory = tempfile::tempdir().unwrap();711+ let export_path = directory.path().join("results.md");712+ let output = hyperfine_debug()713+ .args([714+ "--style=basic",715+ "--runs=1",716+ "--sort=command",717+ "--reference",718+ "sleep 2",719+ "--reference-name",720+ "baseline",721+ "--export-markdown",722+ ])723+ .arg(&export_path)724+ .args(["sleep 1", "sleep 2", "sleep 3"])725+ .output()726+ .unwrap();727+ assert!(output.status.success(), "{:?}", output);728+ let stdout = String::from_utf8(output.stdout).unwrap();729+ let comparison = stdout.split_once("Relative speed comparison\n").unwrap().1;730+ for (name, factor) in [731+ ("baseline (reference)", "1.00"),732+ ("sleep 1 (faster)", "2.00"),733+ ("sleep 2 (same speed)", "1.00"),734+ ("sleep 3 (slower)", "1.50"),735 ] {727- let output = hyperfine_debug()728- .args(["--style=basic", "--runs=2", "--sort=command"])729- .args(args)730- .output()736+ let row = comparison.lines().find(|line| line.contains(name)).unwrap();737+ assert!(row.trim_start().starts_with(factor), "{}", row);738+ }739+ let markdown = std::fs::read_to_string(export_path).unwrap();740+ for (command, relative) in [741+ ("baseline", "1.00 (reference)"),742+ ("sleep 1", "2.00 (faster)"),743+ ("sleep 2", "1.00 (same speed)"),744+ ("sleep 3", "1.50 (slower)"),745+ ] {746+ let row = markdown747+ .lines()748+ .find(|line| line.contains(command))749 .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- );750+ assert!(row.ends_with(&format!("| {relative} |")), "{}", row);751 }752+753+ // Equal zero times have no meaningful relative factor.754+ let output = hyperfine_debug()755+ .args([756+ "--style=none",757+ "--runs=1",758+ "--export-markdown=-",759+ "--reference",760+ "sleep 0",761+ "--reference-name",762+ "baseline",763+ "sleep 0",764+ ])765+ .output()766+ .unwrap();767+ assert!(output.status.success(), "{:?}", output);768+ let markdown = String::from_utf8(output.stdout).unwrap();769+ let row = markdown770+ .lines()771+ .find(|line| line.contains("sleep 0"))772+ .unwrap();773+ assert!(row.ends_with("| N/A |"), "{}", row);774 }775 776 #[test]777 fn shows_reference_name() {84 unmodified lines862 ));863 }864 }865 832-#[test]833-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-866 #[cfg(unix)]867 #[test]868 fn selects_reference_with_parameterized_prepare() {869 let directory = tempfile::tempdir().unwrap();21 unmodified lines891 .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+ for (number, delay) in ["0.2", "0.4", "0.6"].iter().enumerate() {896+ assert!(897+ stdout.contains(&format!(898+ "Benchmark {}: echo a (delay = {})",899+ number + 1,900+ delay901+ )),902+ "{}",903+ stdout904+ );905+ }906 assert!(stdout.contains("echo a (delay = 0.4) ran"), "{}", stdout);907 908 let mut csv = csv::Reader::from_path(csv_path).unwrap();909 assert!(csv910 .headers()911 .unwrap()912 .iter()913 .any(|header| header == "parameter_delay"));903- let records: Vec<_> = csv.records().map(|record| record.unwrap()).collect();904- assert_eq!(records.len(), 3);914+ assert_eq!(915+ csv.records().collect::<Result<Vec<_>, _>>().unwrap().len(),916+ 3917+ );918 let json: serde_json::Value =919 serde_json::from_slice(&std::fs::read(json_path).unwrap()).unwrap();920 let results = json["results"].as_array().unwrap();921 assert_eq!(results.len(), 3);6 unmodified lines928 );929 }930 931 #[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-946-#[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-971-#[test]972-fn rejects_unmatched_parameterized_reference_before_creating_export() {932+fn rejects_unmatched_reference_before_export_or_setup() {933 let directory = tempfile::tempdir().unwrap();934 let export_path = directory.path().join("results.csv");935 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();936+ 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- ));937 998- assert_eq!(999- std::fs::read_to_string(&export_path).unwrap(),1000- "previous contents"1001- );1002- assert!(!marker_path.exists());1003- }938+ hyperfine()939+ .args(["--reference", "sleep 1", "-P", "secs", "2", "3", "--setup"])940+ .arg(format!("echo touched > \"{}\"", marker_path.display()))941+ .arg("--export-csv")942+ .arg(&export_path)943+ .arg("sleep {secs}")944+ .assert()945+ .failure()946+ .stdout(predicate::str::is_empty())947+ .stderr(predicate::str::contains(948+ "does not match any parameterized benchmark",949+ ));950+ assert_eq!(951+ std::fs::read_to_string(export_path).unwrap(),952+ "previous contents"953+ );954+ assert!(!marker_path.exists());955 }956 957 #[test]958 fn rejects_ambiguous_parameterized_reference() {1008- for args in [1009- vec![959+ hyperfine_debug()960+ .args([961 "-L",962 "x",963 "1,2",964 "--command-name",965 "case",966 "--reference",967 "case",968 "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}",969 ])970 .assert()971 .failure()972 .stderr(predicate::str::contains(1048- "--reference-name cannot be used with a parameterized reference",973+ "matches multiple parameterized benchmarks",974 ));975 }976 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-977 #[cfg(unix)]978 #[test]979 fn intermediate_markdown_waits_for_selected_reference() {980 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([981+ let export_path = directory.path().join("results.md");982+ hyperfine()983+ .args([984 "--style=none",985 "--shell=none",986 "--runs=1",987 "-L",988 "delay",989 "0.01,0.02,0.03",990 "--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- }991+ "sleep 0.02",992+ "--prepare",993+ "true",994+ "--prepare",995+ "false",996+ "--prepare",997+ "true",998+ "--export-markdown",999+ ])1000+ .arg(&export_path)1001+ .arg("sleep {delay}")1002+ .assert()1003+ .failure();1004+ let markdown = std::fs::read_to_string(export_path).unwrap();1005+ let row = markdown1006+ .lines()1007+ .find(|line| line.contains("sleep 0.01"))1008+ .unwrap();1009+ assert!(row.ends_with("| N/A |"), "{}", row);1010 }1011 1012 #[test]1013 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- }1014+ let output = hyperfine_debug()1015+ .args([1016+ "--style=none",1017+ "--runs=1",1018+ "--export-markdown=-",1019+ "-P",1020+ "x",1021+ "1",1022+ "3",1023+ "--command-name",1024+ "case-{x}",1025+ "--reference",1026+ "case-2",1027+ "sleep {x}",1028+ ])1029+ .output()1030+ .unwrap();1031+ assert!(output.status.success(), "{:?}", output);1032+ let stdout = String::from_utf8(output.stdout).unwrap();1033+ for (command, relative) in [1034+ ("case-1", "2.00 (faster)"),1035+ ("case-2", "1.00 (reference)"),1036+ ("case-3", "1.50 (slower)"),1037+ ] {1038+ let row = stdout.lines().find(|line| line.contains(command)).unwrap();1039+ assert!(row.ends_with(&format!("| {relative} |")), "{}", row);1040 }1041 }1042 1043 #[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]1044 fn intermediate_results_are_not_exported_to_stdout() {1045 let _settings = snapshot_settings().bind_to_scope();1046 assert_cmd_snapshot!(hyperfine_debug()1047 .arg("--style=none") // To only see the Markdown export on stdout232 unmodified linesmodified:README.md-10 removed
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-101 If you need a unique value for each individual run of a benchmark command, hyperfine also exposes102 the zero-based `$HYPERFINE_ITERATION` environment variable inside the benchmarked command itself:103 ```sh104 hyperfine 'my-command > output-${HYPERFINE_ITERATION}.log'250 unmodified lines