Skip to content
Myr

Support matrices of independent parameter lists

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

This patch permits the `-L`/`--parameter-list` argument to appear multiple times. Each additional parameter increases the dimensionality of the parameter matrix. One benchmark will be run for each combination of parameters (i.e., the benchmark space is the Cartesian product of the parameter spaces). For now, `--parameter-list` and `--parameter-scan` are still mutually exclusive. If desired, a follow-up change could similarly permit multiple occurrences of `--parameter-scan` and also permit use of both listed and scanned parameters together. (After all, `--parameter-scan` can be thought of as syntactic sugar for a parameter list.) This implementation is a little profligate with memory usage for `BenchmarkResult`s: each result contains a separate copy of all parameter names (as `String`s). This could be done away with by threading lifetimes through the `BenchmarkResult`s, or by ref-counting the names. Because `BenchmarkResult`s now have maps with arbitrary key sets, we can no longer use `serde` to serialize them to CSV. But a CSV writer is easy to write by hand, so we just do that. Fixes #253. Test Plan: Some unit tests included. As an integration test, try: ``` cargo run --release -- --runs 10 \ -L foo foo1,foo2 -L bar bar9,bar8 \ 'echo {foo} {bar}' \ 'printf "%s\n" {foo} {bar}' \ --export-csv /tmp/out ``` with all the export formats.

authored by William Chargin · committed by David Peter · parent 5a80a23 · Browse files · 9 files+286 added−78 removed
This commit

State

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

Trailers

  • wchargin-branch: param-list-matrix
  • wchargin-source: 11051ab222c9de0fbc6ac6a080fbca48e05996c2

Diff stats

9 files+286 added−78 removed

  • other:+286 added−78 removed

9 files+286 added−78 removed

modified:src/hyperfine/export/asciidoc.rs+21 added-8 removed
81 unmodified lines
8283/// Ensure each table row is generated properly84#[test]85fn test_asciidoc_table_row() {86 use std::collections::BTreeMap;87 let result = BenchmarkResult::new(88 String::from("sleep 1"), // command89 0.10491992406666667, // mean90 0.00397851689425097, // stddev
7 unmodified lines
98 0.1003342584,99 0.10745223440000001,100 0.10697327940000001,101 ],101 None, // param102 BTreeMap::new(), // param103 );104105 let expms = format!(106 "| `{}`\n\
27 unmodified lines
134135/// Ensure commands get properly escaped136#[test]137fn test_asciidoc_table_row_command_escape() {138 use std::collections::BTreeMap;139 let result = BenchmarkResult::new(140 String::from("sleep 1|"), // command141 0.10491992406666667, // mean142 0.00397851689425097, // stddev
7 unmodified lines
150 0.1003342584,151 0.10745223440000001,152 0.10697327940000001,153 ],152 None, // param154 BTreeMap::new(), // param155 );156 let exps = format!(157 "| `sleep 1\\|`\n\158 | {} ± {}\n\
11 unmodified lines
170171/// Integration test172#[test]173fn test_asciidoc() {174 use std::collections::BTreeMap;175 let exporter = AsciidocExporter::default();176 // NOTE: results are fabricated, unlike above177 let results = vec![178 BenchmarkResult::new(176 String::from("command | 1"),179 String::from("FOO=1 BAR=2 command | 1"),180 1.0,181 2.0,182 1.0,183 3.0,184 4.0,185 5.0,186 6.0,187 vec![7.0, 8.0, 9.0],185 None,188 {189 let mut params = BTreeMap::new();190 params.insert("foo".into(), "1".into());191 params.insert("bar".into(), "2".into());192 params193 },194 ),195 BenchmarkResult::new(188 String::from("command | 2"),196 String::from("FOO=1 BAR=7 command | 2"),197 11.0,198 12.0,199 11.0,200 13.0,201 14.0,202 15.0,203 16.0,204 vec![17.0, 18.0, 19.0],197 None,205 {206 let mut params = BTreeMap::new();207 params.insert("foo".into(), "1".into());208 params.insert("bar".into(), "7".into());209 params210 },211 ),212 ];213 // NOTE: only testing with s, s/ms is tested elsewhere214 let exps: String = String::from(215 "[cols=\"<,>,>\"]\n\216 |===\n\217 | Command | Mean [s] | Min…Max [s]\n\218 \n\206 | `command \\| 1`\n\219 | `FOO=1 BAR=2 command \\| 1`\n\220 | 1.000 ± 2.000\n\221 | 5.000…6.000\n\222 \n\210 | `command \\| 2`\n\223 | `FOO=1 BAR=7 command \\| 2`\n\224 | 11.000 ± 12.000\n\225 | 15.000…16.000\n\226 |===\n\227 ",
6 unmodified lines
modified:src/hyperfine/export/csv.rs+83 added-5 removed
1 unmodified line
23use crate::hyperfine::types::BenchmarkResult;4use crate::hyperfine::units::Unit;56use std::borrow::Cow;7use std::io::{Error, ErrorKind, Result};89use csv::WriterBuilder;10
2 unmodified lines
1314impl Exporter for CsvExporter {15 fn serialize(&self, results: &[BenchmarkResult], _unit: Option<Unit>) -> Result<Vec<u8>> {16 let mut writer = WriterBuilder::new().from_writer(vec![]);16 for res in results {17 // The list of times cannot be exported to the CSV file - remove it:18 let mut result = res.clone();19 result.times = None;1721 writer.serialize(result)?;18 {19 let mut headers: Vec<String> = [20 // The list of times cannot be exported to the CSV file - omit it.21 "command", "mean", "stddev", "median", "user", "system", "min", "max",22 ]23 .iter()24 .map(|x| (*x).to_string())25 .collect();26 if let Some(res) = results.first() {27 for param_name in res.parameters.keys() {28 headers.push(format!("parameter_{}", param_name));29 }30 }31 writer.write_record(headers)?;32 }3334 for res in results {35 let mut fields = Vec::new();36 fields.push(Cow::Borrowed(res.command.as_bytes()));37 for f in &[38 res.mean, res.stddev, res.median, res.user, res.system, res.min, res.max,39 ] {40 fields.push(Cow::Owned(f.to_string().into_bytes()))41 }42 for v in res.parameters.values() {43 fields.push(Cow::Borrowed(v.as_bytes()))44 }45 writer.write_record(fields)?;46 }4748 writer49 .into_inner()50 .map_err(|e| Error::new(ErrorKind::Other, e))51 }52}5354#[test]55fn test_csv() {56 use std::collections::BTreeMap;57 let exporter = CsvExporter::default();5859 // NOTE: results are fabricated60 let results = vec![61 BenchmarkResult::new(62 String::from("FOO=one BAR=two command | 1"),63 1.0,64 2.0,65 1.0,66 3.0,67 4.0,68 5.0,69 6.0,70 vec![7.0, 8.0, 9.0],71 {72 let mut params = BTreeMap::new();73 params.insert("foo".into(), "one".into());74 params.insert("bar".into(), "two".into());75 params76 },77 ),78 BenchmarkResult::new(79 String::from("FOO=one BAR=seven command | 2"),80 11.0,81 12.0,82 11.0,83 13.0,84 14.0,85 15.0,86 16.5,87 vec![17.0, 18.0, 19.0],88 {89 let mut params = BTreeMap::new();90 params.insert("foo".into(), "one".into());91 params.insert("bar".into(), "seven".into());92 params93 },94 ),95 ];96 let exps: String = String::from(97 "command,mean,stddev,median,user,system,min,max,parameter_bar,parameter_foo\n\98 FOO=one BAR=two command | 1,1,2,1,3,4,5,6,two,one\n\99 FOO=one BAR=seven command | 2,11,12,11,13,14,15,16.5,seven,one\n\100 ",101 );102 let gens =103 String::from_utf8(exporter.serialize(&results, Some(Unit::Second)).unwrap()).unwrap();104105 assert_eq!(exps, gens);106}
modified:src/hyperfine/export/markdown.rs+12 added-8 removed
80 unmodified lines
81/// This also demonstrates that the first entry's units (ms) are used to set82/// the units for all entries when the time unit is not given.83#[test]84fn test_markdown_format_ms() {85 use std::collections::BTreeMap;86 let exporter = MarkdownExporter::default();8788 let mut timing_results = vec![];89
6 unmodified lines
96 0.0011, // system_mean97 0.1023, // min98 0.1080, // max99 vec![0.1, 0.1, 0.1], // times99 None, // parameter100 BTreeMap::new(), // parameter101 ));102103 timing_results.push(BenchmarkResult::new(104 String::from("sleep 2"),
4 unmodified lines
109 0.0012, // system_mean110 2.0020, // min111 2.0080, // max112 vec![2.0, 2.0, 2.0], // times112 None, // parameter113 BTreeMap::new(), // parameter114 ));115116 let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();117
11 unmodified lines
129/// This (again) demonstrates that the first entry's units (s) are used to set130/// the units for all entries when the time unit is not given.131#[test]132fn test_markdown_format_s() {133 use std::collections::BTreeMap;134 let exporter = MarkdownExporter::default();135136 let mut timing_results = vec![];137
6 unmodified lines
144 0.0012, // system_mean145 2.0020, // min146 2.0080, // max147 vec![2.0, 2.0, 2.0], // times146 None, // parameter148 BTreeMap::new(), // parameter149 ));150151 timing_results.push(BenchmarkResult::new(152 String::from("sleep 0.1"),
4 unmodified lines
157 0.0011, // system_mean158 0.1023, // min159 0.1080, // max160 vec![0.1, 0.1, 0.1], // times159 None, // parameter161 BTreeMap::new(), // parameter162 ));163164 let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();165
10 unmodified lines
176177/// The given time unit (s) is used to set the units for all entries.178#[test]179fn test_markdown_format_time_unit_s() {180 use std::collections::BTreeMap;181 let exporter = MarkdownExporter::default();182183 let mut timing_results = vec![];184
6 unmodified lines
191 0.0011, // system_mean192 0.1023, // min193 0.1080, // max194 vec![0.1, 0.1, 0.1], // times192 None, // parameter195 BTreeMap::new(), // parameter196 ));197198 timing_results.push(BenchmarkResult::new(199 String::from("sleep 2"),
4 unmodified lines
204 0.0012, // system_mean205 2.0020, // min206 2.0080, // max207 vec![2.0, 2.0, 2.0], // times205 None, // parameter208 BTreeMap::new(), // parameter209 ));210211 let formatted = String::from_utf8(212 exporter
16 unmodified lines
229/// This (again) demonstrates that the given time unit (ms) is used to set230/// the units for all entries.231#[test]232fn test_markdown_format_time_unit_ms() {233 use std::collections::BTreeMap;234 let exporter = MarkdownExporter::default();235236 let mut timing_results = vec![];237
6 unmodified lines
244 0.0012, // system_mean245 2.0020, // min246 2.0080, // max247 vec![2.0, 2.0, 2.0], // times244 None, // parameter248 BTreeMap::new(), // parameter249 ));250251 timing_results.push(BenchmarkResult::new(252 String::from("sleep 0.1"),
4 unmodified lines
257 0.0011, // system_mean258 0.1023, // min259 0.1080, // max260 vec![0.1, 0.1, 0.1], // times257 None, // parameter261 BTreeMap::new(), // parameter262 ));263264 let formatted = String::from_utf8(265 exporter
15 unmodified lines
modified:src/hyperfine/app.rs+4 added-2 removed
1 unmodified line
2use atty::Stream;3use clap::{crate_version, App, AppSettings, Arg, ArgMatches};4use std::ffi::OsString;56pub fn get_arg_matches<T>(args: T) -> ArgMatches<'static>6pub fn get_arg_matches<I, T>(args: I) -> ArgMatches<'static>7where8 T: Iterator<Item = OsString>,8 I: IntoIterator<Item = T>,9 T: Into<OsString> + Clone,10{11 let app = build_app();12 app.get_matches_from(args)13}
120 unmodified lines
134 Arg::with_name("parameter-list")135 .long("parameter-list")136 .short("L")137 .takes_value(true)138 .multiple(true)139 .allow_hyphen_values(true)140 .value_names(&["VAR", "VALUES"])141 .conflicts_with_all(&["parameter-scan", "parameter-step-size"])142 .help(
89 unmodified lines
modified:src/hyperfine/benchmark.rs+8 added-17 removed
221 unmodified lines
222 &values[0]223 } else {224 &values[num]225 };226 match cmd.get_parameter() {227 Some((param, value)) => {228 Command::new_parametrized(preparation_command, param, value.clone())226 Command::new_parametrized(preparation_command, cmd.get_parameters().clone())229 }230 None => Command::new(preparation_command),231 }227 });228229 // Warmup phase230 if options.warmup_count > 0 {
177 unmodified lines
408 println!(" ");409 }410411 // Run cleanup command417 let cleanup_cmd =418 options419 .cleanup_command420 .as_ref()421 .map(|cleanup_command| match cmd.get_parameter() {422 Some((param, value)) => {423 Command::new_parametrized(cleanup_command, param, value.clone())424 }425 None => Command::new(cleanup_command),426 });412 let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {413 Command::new_parametrized(cleanup_command, cmd.get_parameters().clone())414 });415 run_cleanup_command(&options.shell, &cleanup_cmd, options.show_output)?;416417 Ok(BenchmarkResult::new(418 cmd.get_shell_command(),
4 unmodified lines
423 system_mean,424 t_min,425 t_max,426 times_real,439 cmd.get_parameter().as_ref().map(|p| p.1.to_string()),427 cmd.get_parameters()428 .iter()429 .map(|(name, value)| ((*name).to_string(), value.to_string()))430 .collect(),431 ))432}
modified:src/hyperfine/internal.rs+2 added-1 removed
126 unmodified lines
127128#[test]129fn test_compute_relative_speed() {130 use approx::assert_relative_eq;131 use std::collections::BTreeMap;132133 let create_result = |name: &str, mean| BenchmarkResult {134 command: name.into(),135 mean,
3 unmodified lines
139 system: 0.0,140 min: mean,141 max: mean,142 times: None,142 parameter: None,143 parameters: BTreeMap::new(),144 };145146 let results = vec![147 create_result("cmd1", 3.0),
71 unmodified lines
modified:src/hyperfine/parameter_range.rs+1 added-2 removed
92 unmodified lines
93 for value in param_range {94 for cmd in &command_strings {95 commands.push(Command::new_parametrized(96 cmd,97 param_name,98 ParameterValue::Numeric(value.into()),97 vec![(param_name, ParameterValue::Numeric(value.into()))],98 ));99 }100 }101 Ok(commands)
81 unmodified lines
modified:src/hyperfine/types.rs+55 added-22 removed
1use rust_decimal::Decimal;2/// This module contains common internal types.3use serde::*;4use std::collections::BTreeMap;5use std::fmt;67use crate::hyperfine::units::{Second, Unit};8
2 unmodified lines
1112#[cfg(windows)]13pub const DEFAULT_SHELL: &str = "cmd.exe";1414#[derive(Debug, Clone, Serialize, Copy, PartialEq)]15#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq)]16#[serde(untagged)]17pub enum NumericType {18 Int(i32),19 Decimal(Decimal),
19 unmodified lines
39 NumericType::Decimal(self)40 }41}4242#[derive(Debug, Clone)]43#[derive(Debug, Clone, PartialEq, Eq)]44pub enum ParameterValue {45 Text(String),46 Numeric(NumericType),47}
7 unmodified lines
55 }56}5758/// A command that should be benchmarked.58#[derive(Debug, Clone)]59#[derive(Debug, Clone, PartialEq, Eq)]60pub struct Command<'a> {61 /// The command that should be executed (without parameter substitution)62 expression: &'a str,6363 /// A possible parameter value.64 parameter: Option<(&'a str, ParameterValue)>,64 /// Zero or more parameter values.65 parameters: Vec<(&'a str, ParameterValue)>,66}6768impl<'a> Command<'a> {69 pub fn new(expression: &'a str) -> Command<'a> {70 Command {71 expression,71 parameter: None,72 parameters: Vec::new(),73 }74 }7576 pub fn new_parametrized(77 expression: &'a str,77 parameter: &'a str,78 value: ParameterValue,78 parameters: Vec<(&'a str, ParameterValue)>,79 ) -> Command<'a> {80 Command {81 expression,82 parameter: Some((parameter, value)),82 parameters,83 }84 }8586 pub fn get_shell_command(&self) -> String {87 match &self.parameter {88 Some((param_name, param_value)) => self.expression.replace(89 &format!("{{{param_name}}}", param_name = param_name),90 &param_value.to_string(),91 ),92 None => self.expression.into(),87 let mut result = String::new();88 let mut replacements = BTreeMap::<String, String>::new();89 for (param_name, param_value) in &self.parameters {90 replacements.insert(91 format!("{{{param_name}}}", param_name = param_name),92 param_value.to_string(),93 );94 }95 let mut remaining = self.expression;96 // Manually replace consecutive occurrences to avoid double-replacing: e.g.,97 //98 // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'99 //100 // should not ever run 'echo baz baz'. See `test_get_shell_command_nonoverlapping`.101 'outer: while let Some(head) = remaining.chars().next() {102 for (k, v) in &replacements {103 if remaining.starts_with(k.as_str()) {104 result.push_str(&v);105 remaining = &remaining[k.len()..];106 continue 'outer;107 }108 }109 result.push(head);110 remaining = &remaining[head.len_utf8()..];111 }112 result113 }11496 pub fn get_parameter(&self) -> &Option<(&'a str, ParameterValue)> {97 &self.parameter115 pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {116 &self.parameters117 }118}119120#[test]121fn test_get_shell_command_nonoverlapping() {122 let cmd = Command::new_parametrized(123 "echo {foo} {bar}",124 vec![125 ("foo", ParameterValue::Text("{bar} baz".into())),126 ("bar", ParameterValue::Text("quux".into())),127 ],128 );129 assert_eq!(cmd.get_shell_command(), "echo {bar} baz quux");130}131132impl<'a> fmt::Display for Command<'a> {133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {134 write!(f, "{}", self.get_shell_command())135 }
93 unmodified lines
229 }230}231232/// Set of values that will be exported.233// NOTE: `serde` is used for JSON serialization, but not for CSV serialization due to the234// `parameters` map. Update `src/hyperfine/export/csv.rs` with new fields, as appropriate.235#[derive(Debug, Default, Clone, Serialize, PartialEq)]236pub struct BenchmarkResult {237 /// The command that was run238 pub command: String,
22 unmodified lines
261 /// All run time measurements262 #[serde(skip_serializing_if = "Option::is_none")]263 pub times: Option<Vec<Second>>,264232 /// Any parameter used233 #[serde(skip_serializing_if = "Option::is_none")]234 pub parameter: Option<String>,265 /// Any parameter values used266 #[serde(skip_serializing_if = "BTreeMap::is_empty")]267 pub parameters: BTreeMap<String, String>,268}269270impl BenchmarkResult {271 /// Create a new entry with the given values.
6 unmodified lines
278 system: Second,279 min: Second,280 max: Second,281 times: Vec<Second>,249 parameter: Option<String>,282 parameters: BTreeMap<String, String>,283 ) -> Self {284 BenchmarkResult {285 command,286 mean,
3 unmodified lines
290 system,291 min,292 max,293 times: Some(times),261 parameter,294 parameters,295 }296 }297}
modified:src/main.rs+100 added-13 removed
1use std::cmp;2use std::collections::BTreeMap;3use std::env;4use std::io;56use atty::Stream;
200 unmodified lines
207 match get_parameterized_commands(command_strings, args, step_size) {208 Ok(commands) => commands,209 Err(e) => error(&e.to_string()),210 }210 } else if let Some(mut args) = matches.values_of("parameter-list") {211 let param_name = args.next().unwrap();212 let param_list_str = args.next().unwrap();213214 let param_list = tokenize(param_list_str);211 } else if let Some(args) = matches.values_of("parameter-list") {212 let args: Vec<_> = args.collect();213 let param_names_and_values: Vec<(&str, Vec<String>)> = args214 .chunks_exact(2)215 .map(|pair| {216 let name = pair[0];217 let list_str = pair[1];218 (name, tokenize(list_str))219 })220 .collect();221 {222 let dupes = find_dupes(param_names_and_values.iter().map(|(name, _)| *name));223 if !dupes.is_empty() {224 error(&format!("duplicate parameter names: {}", &dupes.join(", ")))225 }226 }227 let command_list = command_strings.collect::<Vec<&str>>();228217 let mut commands = Vec::with_capacity(param_list.len() * command_list.len());229 let dimensions: Vec<usize> = std::iter::once(command_list.len())230 .chain(231 param_names_and_values232 .iter()233 .map(|(_, values)| values.len()),234 )235 .collect();236 let param_space_size = dimensions.iter().product();237 if param_space_size == 0 {238 return Vec::new();239 }240219 for value in param_list {220 for cmd in &command_list {221 commands.push(Command::new_parametrized(222 cmd,223 param_name,224 ParameterValue::Text(value.clone()),225 ));241 let mut commands = Vec::with_capacity(param_space_size);242 let mut index = vec![0usize; dimensions.len()];243 'outer: loop {244 let (command_index, params_indices) = index.split_first().unwrap();245 let parameters = param_names_and_values246 .iter()247 .zip(params_indices)248 .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone())))249 .collect();250 commands.push(Command::new_parametrized(251 command_list[*command_index],252 parameters,253 ));254255 // Increment index, exiting loop on overflow.256 for (i, n) in index.iter_mut().zip(dimensions.iter()) {257 *i += 1;258 if *i < *n {259 continue 'outer;260 } else {261 *i = 0;262 }263 }264 break 'outer;265 }266267 commands268 } else {269 command_strings.map(Command::new).collect()270 }271}272273/// Finds all the strings that appear multiple times in the input iterator, returning them in274/// sorted order. If no string appears more than once, the result is an empty vector.275fn find_dupes<'a, I: IntoIterator<Item = &'a str>>(i: I) -> Vec<&'a str> {276 let mut counts = BTreeMap::<&'a str, usize>::new();277 for s in i {278 *counts.entry(s).or_default() += 1;279 }280 counts281 .into_iter()282 .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })283 .collect()284}285286#[test]287fn test_build_commands_cross_product() {288 let matches = get_arg_matches(vec![289 "hyperfine",290 "-L",291 "foo",292 "a,b",293 "-L",294 "bar",295 "z,y",296 "echo {foo} {bar}",297 "printf '%s\n' {foo} {bar}",298 ]);299 let result = build_commands(&matches);300301 // Iteration order: command list first, then parameters in listed order (here, "foo" before302 // "bar", which is distinct from their sorted order), with parameter values in listed order.303 let pv = |s: &str| ParameterValue::Text(s.to_string());304 let cmd = |cmd: usize, foo: &str, bar: &str| {305 let expression = ["echo {foo} {bar}", "printf '%s\n' {foo} {bar}"][cmd];306 let params = vec![("foo", pv(foo)), ("bar", pv(bar))];307 Command::new_parametrized(expression, params)308 };309 let expected = vec![310 cmd(0, "a", "z"),311 cmd(1, "a", "z"),312 cmd(0, "b", "z"),313 cmd(1, "b", "z"),314 cmd(0, "a", "y"),315 cmd(1, "a", "y"),316 cmd(0, "b", "y"),317 cmd(1, "b", "y"),318 ];319 assert_eq!(result, expected);320}