Skip to content
Myr

Add new --sort option

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This adds a new `--sort` option to choose the way in which the results in the speed comparison and the markup exports are ordered. closes #614 closes #601

authored by David Peter · committed by David Peter · parent 2393de0 · Browse files · 12 files+285 added−89 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+285 added−89 removed

  • tests:+25 added−0 removed
  • other:+260 added−89 removed

12 files+285 added−89 removed

modified:src/benchmark/relative_speed.rs+22 added-8 removed
1use std::cmp::Ordering;23use super::benchmark_result::BenchmarkResult;4use crate::util::units::Scalar;4use crate::{options::SortOrder, util::units::Scalar};56#[derive(Debug)]7pub struct BenchmarkResultWithRelativeSpeed<'a> {8 pub result: &'a BenchmarkResult,
15 unmodified lines
2425fn compute_relative_speeds<'a>(26 results: &'a [BenchmarkResult],27 fastest: &'a BenchmarkResult,28 sort_order: SortOrder,29) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> {29 results30 let mut results: Vec<_> = results31 .iter()32 .map(|result| {33 let is_fastest = result == fastest;34
26 unmodified lines
61 relative_speed_stddev: ratio_stddev,62 is_fastest,63 }64 })64 .collect()65 .collect();6667 match sort_order {68 SortOrder::Command => {}69 SortOrder::MeanTime => {70 results.sort_unstable_by(|r1, r2| compare_mean_time(r1.result, r2.result));71 }72 }7374 results75}7677pub fn compute_with_check(78 results: &[BenchmarkResult],79 sort_order: SortOrder,80) -> Option<Vec<BenchmarkResultWithRelativeSpeed>> {81 let fastest = fastest_of(results);8283 if fastest.mean == 0.0 {84 return None;85 }8676 Some(compute_relative_speeds(results, fastest))87 Some(compute_relative_speeds(results, fastest, sort_order))88}8990/// Same as compute_with_check, potentially resulting in relative speeds of infinity80pub fn compute(results: &[BenchmarkResult]) -> Vec<BenchmarkResultWithRelativeSpeed> {91pub fn compute(92 results: &[BenchmarkResult],93 sort_order: SortOrder,94) -> Vec<BenchmarkResultWithRelativeSpeed> {95 let fastest = fastest_of(results);9683 compute_relative_speeds(results, fastest)97 compute_relative_speeds(results, fastest, sort_order)98}99100#[cfg(test)]101fn create_result(name: &str, mean: Scalar) -> BenchmarkResult {
24 unmodified lines
126 create_result("cmd2", 2.0),127 create_result("cmd3", 5.0),128 ];129116 let annotated_results = compute_with_check(&results).unwrap();130 let annotated_results = compute_with_check(&results, SortOrder::Command).unwrap();131132 assert_relative_eq!(1.5, annotated_results[0].relative_speed);133 assert_relative_eq!(1.0, annotated_results[1].relative_speed);134 assert_relative_eq!(2.5, annotated_results[2].relative_speed);
2 unmodified lines
137#[test]138fn test_compute_relative_speed_for_zero_times() {139 let results = vec![create_result("cmd1", 1.0), create_result("cmd2", 0.0)];140127 let annotated_results = compute_with_check(&results);141 let annotated_results = compute_with_check(&results, SortOrder::Command);142143 assert!(annotated_results.is_none());144}
modified:src/benchmark/scheduler.rs+54 added-23 removed
4 unmodified lines
5use super::{relative_speed, Benchmark};67use crate::command::Commands;8use crate::export::ExportManager;9use crate::options::{ExecutorKind, Options, OutputStyleOption};9use crate::options::{ExecutorKind, Options, OutputStyleOption, SortOrder};1011use anyhow::Result;1213pub struct Scheduler<'a> {
31 unmodified lines
45 .push(Benchmark::new(number, cmd, self.options, &*executor).run()?);4647 // We export results after each individual benchmark, because48 // we would risk losing them if a later benchmark fails.49 self.export_manager.write_results(&self.results, true)?;49 self.export_manager.write_results(50 &self.results,51 self.options.sort_order_exports,52 true,53 )?;54 }5556 Ok(())57 }
6 unmodified lines
64 if self.results.len() < 2 {65 return;66 }6764 if let Some(mut annotated_results) = relative_speed::compute_with_check(&self.results) {65 annotated_results.sort_by(|l, r| relative_speed::compare_mean_time(l.result, r.result));68 if let Some(annotated_results) = relative_speed::compute_with_check(69 &self.results,70 self.options.sort_order_speed_comparison,71 ) {72 match self.options.sort_order_speed_comparison {73 SortOrder::MeanTime => {74 println!("{}", "Summary".bold());7567 let fastest = &annotated_results[0];68 let others = &annotated_results[1..];76 let fastest = annotated_results.iter().find(|r| r.is_fastest).unwrap();77 let others = annotated_results.iter().filter(|r| !r.is_fastest);7870 println!("{}", "Summary".bold());71 println!(72 " {} ran",73 fastest.result.command_with_unused_parameters.cyan()74 );79 println!(80 " {} ran",81 fastest.result.command_with_unused_parameters.cyan()82 );8376 for item in others {77 println!(78 "{}{} times faster than {}",79 format!("{:8.2}", item.relative_speed).bold().green(),80 if let Some(stddev) = item.relative_speed_stddev {81 format!(" ± {}", format!("{:.2}", stddev).green())82 } else {83 "".into()84 },85 &item.result.command_with_unused_parameters.magenta()86 );84 for item in others {85 println!(86 "{}{} times faster than {}",87 format!("{:8.2}", item.relative_speed).bold().green(),88 if let Some(stddev) = item.relative_speed_stddev {89 format!(" ± {}", format!("{:.2}", stddev).green())90 } else {91 "".into()92 },93 &item.result.command_with_unused_parameters.magenta()94 );95 }96 }97 SortOrder::Command => {98 println!("{}", "Relative speed comparison".bold());99100 for item in annotated_results {101 println!(102 " {}{} {}",103 format!("{:10.2}", item.relative_speed).bold().green(),104 if item.is_fastest {105 " ".into()106 } else {107 if let Some(stddev) = item.relative_speed_stddev {108 format!(" ± {}", format!("{:5.2}", stddev).green())109 } else {110 " ".into()111 }112 },113 &item.result.command_with_unused_parameters,114 );115 }116 }117 }118 } else {119 eprintln!(120 "{}: The benchmark comparison could not be computed as some benchmark times are zero. \
7 unmodified lines
128 }129 }130131 pub fn final_export(&self) -> Result<()> {102 self.export_manager.write_results(&self.results, false)132 self.export_manager133 .write_results(&self.results, self.options.sort_order_exports, false)134 }135}
modified:src/export/asciidoc.rs+10 added-3 removed
75 unmodified lines
76 )77}7879#[cfg(test)]80use crate::options::SortOrder;8182#[cfg(test)]83use crate::util::units::Unit;8485#[cfg(test)]86use crate::export::BenchmarkResult;
47 unmodified lines
134 },135 },136 ];137135 let actual =136 String::from_utf8(exporter.serialize(&results, Some(Unit::Second)).unwrap()).unwrap();138 let actual = String::from_utf8(139 exporter140 .serialize(&results, Some(Unit::Second), SortOrder::Command)141 .unwrap(),142 )143 .unwrap();144 let expect = format!(145 "{}146| `FOO=1 BAR=2 command \\| 1` 147| 1.000 ± 2.000
63 unmodified lines
211 ];212213 let actual = String::from_utf8(214 exporter208 .serialize(&results, Some(Unit::MilliSecond))215 .serialize(&results, Some(Unit::MilliSecond), SortOrder::Command)216 .unwrap(),217 )218 .unwrap();219 let expect = format!(
19 unmodified lines
modified:src/export/csv.rs+13 added-3 removed
2 unmodified lines
3use csv::WriterBuilder;45use super::Exporter;6use crate::benchmark::benchmark_result::BenchmarkResult;7use crate::options::SortOrder;8use crate::util::units::Unit;910use anyhow::Result;1112#[derive(Default)]13pub struct CsvExporter {}1415impl Exporter for CsvExporter {15 fn serialize(&self, results: &[BenchmarkResult], _unit: Option<Unit>) -> Result<Vec<u8>> {16 fn serialize(17 &self,18 results: &[BenchmarkResult],19 _unit: Option<Unit>,20 _sort_order: SortOrder,21 ) -> Result<Vec<u8>> {22 let mut writer = WriterBuilder::new().from_writer(vec![]);2324 {25 let mut headers: Vec<Cow<[u8]>> = [
84 unmodified lines
110 FOO=one BAR=two command | 1,1,2,1,3,4,5,6,two,one\n\111 FOO=one BAR=seven command | 2,11,12,11,13,14,15,16.5,seven,one\n\112 ",113 );108 let gens =109 String::from_utf8(exporter.serialize(&results, Some(Unit::Second)).unwrap()).unwrap();114 let gens = String::from_utf8(115 exporter116 .serialize(&results, Some(Unit::Second), SortOrder::Command)117 .unwrap(),118 )119 .unwrap();120121 assert_eq!(exps, gens);122}
modified:src/export/json.rs+7 added-1 removed
1 unmodified line
2use serde_json::to_vec_pretty;34use super::Exporter;5use crate::benchmark::benchmark_result::BenchmarkResult;6use crate::options::SortOrder;7use crate::util::units::Unit;89use anyhow::Result;10
5 unmodified lines
16#[derive(Default)]17pub struct JsonExporter {}1819impl Exporter for JsonExporter {19 fn serialize(&self, results: &[BenchmarkResult], _unit: Option<Unit>) -> Result<Vec<u8>> {20 fn serialize(21 &self,22 results: &[BenchmarkResult],23 _unit: Option<Unit>,24 _sort_order: SortOrder,25 ) -> Result<Vec<u8>> {26 let mut output = to_vec_pretty(&HyperfineSummary { results });27 if let Ok(ref mut content) = output {28 content.push(b'\n');29 }
4 unmodified lines
modified:src/export/markdown.rs+61 added-28 removed
26 unmodified lines
27 format!("`{}`", cmd)28 }29}3031#[cfg(test)]32use crate::options::SortOrder;3334/// Check Markdown-based data row formatting35#[test]36fn test_markdown_formatter_table_data() {37 let formatter = MarkdownExporter::default();
63 unmodified lines
101 parameters: BTreeMap::new(),102 },103 ];104102 let actual = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();105 let actual = String::from_utf8(106 exporter107 .serialize(&timing_results, None, SortOrder::Command)108 .unwrap(),109 )110 .unwrap();111 let expect = format!(112 "{}\113| `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 |114| `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 |
43 unmodified lines
158 parameters: BTreeMap::new(),159 },160 ];161154 let actual = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();162 let actual = String::from_utf8(163 exporter164 .serialize(&timing_results, None, SortOrder::Command)165 .unwrap(),166 )167 .unwrap();168 let expect = format!(169 "{}\170| `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 |171| `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |
14 unmodified lines
186 let exporter = MarkdownExporter::default();187188 let timing_results = vec![189 BenchmarkResult {177 command: String::from("sleep 0.1"),178 command_with_unused_parameters: String::from("sleep 0.1"),179 mean: 0.1057,180 stddev: Some(0.0016),181 median: 0.1057,182 user: 0.0009,183 system: 0.0011,184 min: 0.1023,185 max: 0.1080,186 times: Some(vec![0.1, 0.1, 0.1]),187 exit_codes: vec![Some(0), Some(0), Some(0)],188 parameters: BTreeMap::new(),189 },190 BenchmarkResult {190 command: String::from("sleep 2"),191 command_with_unused_parameters: String::from("sleep 2"),192 mean: 2.0050,193 stddev: Some(0.0020),
5 unmodified lines
199 times: Some(vec![2.0, 2.0, 2.0]),200 exit_codes: vec![Some(0), Some(0), Some(0)],201 parameters: BTreeMap::new(),202 },203 BenchmarkResult {204 command: String::from("sleep 0.1"),205 command_with_unused_parameters: String::from("sleep 0.1"),206 mean: 0.1057,207 stddev: Some(0.0016),208 median: 0.1057,209 user: 0.0009,210 system: 0.0011,211 min: 0.1023,212 max: 0.1080,213 times: Some(vec![0.1, 0.1, 0.1]),214 exit_codes: vec![Some(0), Some(0), Some(0)],215 parameters: BTreeMap::new(),216 },217 ];218219 {206 let actual = String::from_utf8(207 exporter208 .serialize(&timing_results, Some(Unit::Second))209 .unwrap(),210 )211 .unwrap();212 let expect = format!(213 "{}\220 let actual = String::from_utf8(221 exporter222 .serialize(&timing_results, Some(Unit::Second), SortOrder::Command)223 .unwrap(),224 )225 .unwrap();226 let expect = format!(227 "{}\228| `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 |229| `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |230",231 cfg_test_table_header("s".to_string())232 );233234 assert_eq!(expect, actual);235 }236237 {238 let actual = String::from_utf8(239 exporter240 .serialize(&timing_results, Some(Unit::Second), SortOrder::MeanTime)241 .unwrap(),242 )243 .unwrap();244 let expect = format!(245 "{}\246| `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |247| `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 |248",217 cfg_test_table_header("s".to_string())218 );249 cfg_test_table_header("s".to_string())250 );251220 assert_eq!(expect, actual);252 assert_eq!(expect, actual);253 }254}255256/// This (again) demonstrates that the given time unit (ms) is used to set257/// the units for all entries.
37 unmodified lines
295 ];296297 let actual = String::from_utf8(298 exporter266 .serialize(&timing_results, Some(Unit::MilliSecond))299 .serialize(&timing_results, Some(Unit::MilliSecond), SortOrder::Command)300 .unwrap(),301 )302 .unwrap();303 let expect = format!(
9 unmodified lines
modified:src/export/markup.rs+8 added-2 removed
1use crate::benchmark::relative_speed::BenchmarkResultWithRelativeSpeed;2use crate::benchmark::{benchmark_result::BenchmarkResult, relative_speed};3use crate::options::SortOrder;4use crate::output::format::format_duration_value;5use crate::util::units::Unit;67use super::Exporter;
97 unmodified lines
105 }106}107108impl<T: MarkupExporter> Exporter for T {108 fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>> {109 fn serialize(110 &self,111 results: &[BenchmarkResult],112 unit: Option<Unit>,113 sort_order: SortOrder,114 ) -> Result<Vec<u8>> {115 let unit = unit.unwrap_or_else(|| determine_unit_from_results(results));110 let entries = relative_speed::compute(results);116 let entries = relative_speed::compute(results, sort_order);117118 let table = self.table_results(&entries, unit);119 Ok(table.as_bytes().to_vec())120 }
181 unmodified lines
modified:src/export/mod.rs+14 added-3 removed
13 unmodified lines
14use self::markdown::MarkdownExporter;15use self::orgmode::OrgmodeExporter;1617use crate::benchmark::benchmark_result::BenchmarkResult;18use crate::options::SortOrder;19use crate::util::units::Unit;2021use anyhow::{Context, Result};22use clap::ArgMatches;
19 unmodified lines
4243/// Interface for different exporters.44trait Exporter {45 /// Export the given entries in the serialized form.45 fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>>;46 fn serialize(47 &self,48 results: &[BenchmarkResult],49 unit: Option<Unit>,50 sort_order: SortOrder,51 ) -> Result<Vec<u8>>;52}5354pub enum ExportTarget {55 File(String),
65 unmodified lines
121 /// is the final call after all benchmarks have been finished. In the former case,122 /// results are written to all file targets (to always have them up to date, even123 /// if a benchmark fails). In the latter case, we only print to stdout targets (in124 /// order not to clutter the output of hyperfine with intermediate results).119 pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> {125 pub fn write_results(126 &self,127 results: &[BenchmarkResult],128 sort_order: SortOrder,129 intermediate: bool,130 ) -> Result<()> {131 for e in &self.exporters {121 let content = || e.exporter.serialize(results, self.time_unit);132 let content = || e.exporter.serialize(results, self.time_unit, sort_order);133134 match e.target {135 ExportTarget::File(ref filename) => {136 if intermediate {
21 unmodified lines
modified:src/export/orgmode.rs+15 added-3 removed
20 unmodified lines
21 format!("={}=", cmd)22 }23}2425#[cfg(test)]26use crate::options::SortOrder;2728/// Check Emacs org-mode data row formatting29#[test]30fn test_orgmode_formatter_table_data() {31 let exporter = OrgmodeExporter::default();
75 unmodified lines
107 parameters: BTreeMap::new(),108 },109 ];110108 let actual = String::from_utf8(exporter.serialize(&results, None).unwrap()).unwrap();111 let actual = String::from_utf8(112 exporter113 .serialize(&results, None, SortOrder::Command)114 .unwrap(),115 )116 .unwrap();117 let expect = format!(118 "{}\119| =sleep 0.1= | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 |120| =sleep 2= | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 |
45 unmodified lines
166 parameters: BTreeMap::new(),167 },168 ];169162 let actual =163 String::from_utf8(exporter.serialize(&results, Some(Unit::Second)).unwrap()).unwrap();170 let actual = String::from_utf8(171 exporter172 .serialize(&results, Some(Unit::Second), SortOrder::Command)173 .unwrap(),174 )175 .unwrap();176 let expect = format!(177 "{}\178| =sleep 2= | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 |179| =sleep 0.1= | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |
6 unmodified lines
modified:src/cli.rs+32 added-15 removed
159 unmodified lines
160 possible parameter combinations.\n"161 ),162 )163 .arg(164 Arg::new("style")165 .long("style")166 .action(ArgAction::Set)167 .value_name("TYPE")168 .value_parser(["auto", "basic", "full", "nocolor", "color", "none"])169 .help(170 "Set output style type (default: auto). Set this to 'basic' to disable output \171 coloring and interactive elements. Set it to 'full' to enable all effects \172 even if no interactive terminal was detected. Set this to 'nocolor' to \173 keep the interactive output without any colors. Set this to 'color' to keep \174 the colors without any interactive output. Set this to 'none' to disable all \175 the output of the tool.",176 ),177 )178 .arg(164 Arg::new("shell")165 .long("shell")166 .short('S')167 .action(ArgAction::Set)
21 unmodified lines
189 .short('i')190 .help("Ignore non-zero exit codes of the benchmarked programs."),191 )192 .arg(193 Arg::new("style")194 .long("style")195 .action(ArgAction::Set)196 .value_name("TYPE")197 .value_parser(["auto", "basic", "full", "nocolor", "color", "none"])198 .help(199 "Set output style type (default: auto). Set this to 'basic' to disable output \200 coloring and interactive elements. Set it to 'full' to enable all effects \201 even if no interactive terminal was detected. Set this to 'nocolor' to \202 keep the interactive output without any colors. Set this to 'color' to keep \203 the colors without any interactive output. Set this to 'none' to disable all \204 the output of the tool.",205 ),206 )207 .arg(208 Arg::new("sort")209 .long("sort")210 .action(ArgAction::Set)211 .value_name("METHOD")212 .value_parser(["auto", "command", "mean-time"])213 .default_value("auto")214 .hide_default_value(true)215 .help(216 "Specify the sort order of the speed comparison summary and the exported tables for \217 markup formats (Markdown, AsciiDoc, org-mode):\n \218 * 'auto' (default): the speed comparison will be ordered by time and\n \219 the markup tables will be ordered by command (input order).\n \220 * 'command': order benchmarks in the way they were specified\n \221 * 'mean-time': order benchmarks by mean runtime\n"222 ),223 )224 .arg(225 Arg::new("time-unit")226 .long("time-unit")227 .short('u')228 .action(ArgAction::Set)
130 unmodified lines
modified:src/options.rs+24 added
93 unmodified lines
94 /// Disable all the output95 Disabled,96}9798#[derive(Debug, Clone, Copy, PartialEq, Eq)]99pub enum SortOrder {100 Command,101 MeanTime,102}103104/// Bounds for the number of benchmark runs105pub struct RunBounds {106 /// Minimum number of benchmark runs107 pub min: u64,
107 unmodified lines
215216 /// What color mode to use for the terminal output217 pub output_style: OutputStyleOption,218219 /// How to order benchmarks in the relative speed comparison220 pub sort_order_speed_comparison: SortOrder,221222 /// How to order benchmarks in the markup format exports223 pub sort_order_exports: SortOrder,224225 /// Determines how we run commands226 pub executor_kind: ExecutorKind,227228 /// Where input to the benchmarked command comes from
16 unmodified lines
245 preparation_command: None,246 setup_command: None,247 cleanup_command: None,248 output_style: OutputStyleOption::Full,249 sort_order_speed_comparison: SortOrder::MeanTime,250 sort_order_exports: SortOrder::Command,251 executor_kind: ExecutorKind::default(),252 command_output_policy: CommandOutputPolicy::Null,253 time_unit: None,254 command_input_policy: CommandInputPolicy::Null,
104 unmodified lines
359 }360 OutputStyleOption::Disabled => {}361 };362363 (364 options.sort_order_speed_comparison,365 options.sort_order_exports,366 ) = match matches.get_one::<String>("sort").map(|s| s.as_str()) {367 None | Some("auto") => (SortOrder::MeanTime, SortOrder::Command),368 Some("command") => (SortOrder::Command, SortOrder::Command),369 Some("mean-time") => (SortOrder::MeanTime, SortOrder::MeanTime),370 Some(_) => unreachable!("Unknown sort order"),371 };372373 options.executor_kind = if matches.get_flag("no-shell") {374 ExecutorKind::Raw375 } else {376 match (
104 unmodified lines
modified:tests/integration_tests.rs+25 added
396 unmodified lines
397 predicate::str::contains("echo test (branch = master)")398 .and(predicate::str::contains("echo test (branch = feature)")),399 );400}401402#[test]403fn speed_comparison_sort_order() {404 for sort_order in ["auto", "mean-time"] {405 hyperfine_debug()406 .arg("sleep 2")407 .arg("sleep 1")408 .arg(format!("--sort={sort_order}"))409 .assert()410 .success()411 .stdout(predicate::str::contains(412 "sleep 1 ran\n 2.00 ± 0.00 times faster than sleep 2",413 ));414 }415416 hyperfine_debug()417 .arg("sleep 2")418 .arg("sleep 1")419 .arg("--sort=command")420 .assert()421 .success()422 .stdout(predicate::str::contains(423 "2.00 ± 0.00 sleep 2\n 1.00 sleep 1",424 ));425}