Skip to content
Myr

Move build_commands

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 33f8d03 · Browse files · 2 files+209 added−203 removed
This commit

State

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

Diff stats

2 files+209 added−203 removed

  • other:+209 added−203 removed

2 files+209 added−203 removed

modified:src/command.rs+208 added
1use std::collections::BTreeMap;2use std::fmt;34use crate::{error::OptionsError, parameter_range::get_parameterized_commands};56use clap::ArgMatches;78use crate::tokenize::tokenize;9use crate::types::ParameterValue;1011use anyhow::{bail, Result};1213/// A command that should be benchmarked.14#[derive(Debug, Clone, PartialEq, Eq)]15pub struct Command<'a> {16 /// The command name (without parameter substitution)
71 unmodified lines
88 result89 }90}9192/// Build the commands to benchmark93pub fn build_commands(matches: &ArgMatches) -> Result<Vec<Command>> {94 let command_names = matches.values_of("command-name");95 let command_strings = matches.values_of("command").unwrap();9697 if let Some(args) = matches.values_of("parameter-scan") {98 let step_size = matches.value_of("parameter-step-size");99 Ok(get_parameterized_commands(100 command_names,101 command_strings,102 args,103 step_size,104 )?)105 } else if let Some(args) = matches.values_of("parameter-list") {106 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());107108 let args: Vec<_> = args.collect();109 let param_names_and_values: Vec<(&str, Vec<String>)> = args110 .chunks_exact(2)111 .map(|pair| {112 let name = pair[0];113 let list_str = pair[1];114 (name, tokenize(list_str))115 })116 .collect();117 {118 let dupes = find_dupes(param_names_and_values.iter().map(|(name, _)| *name));119 if !dupes.is_empty() {120 bail!("Duplicate parameter names: {}", &dupes.join(", "));121 }122 }123 let command_list = command_strings.collect::<Vec<&str>>();124125 let dimensions: Vec<usize> = std::iter::once(command_list.len())126 .chain(127 param_names_and_values128 .iter()129 .map(|(_, values)| values.len()),130 )131 .collect();132 let param_space_size = dimensions.iter().product();133 if param_space_size == 0 {134 return Ok(Vec::new());135 }136137 // `--command-name` should appear exactly once or exactly B times,138 // where B is the total number of benchmarks.139 let command_name_count = command_names.len();140 if command_name_count > 1 && command_name_count != param_space_size {141 return Err(OptionsError::UnexpectedCommandNameCount(142 command_name_count,143 param_space_size,144 )145 .into());146 }147148 let mut i = 0;149 let mut commands = Vec::with_capacity(param_space_size);150 let mut index = vec![0usize; dimensions.len()];151 'outer: loop {152 let name = command_names153 .get(i)154 .or_else(|| command_names.get(0))155 .copied();156 i += 1;157158 let (command_index, params_indices) = index.split_first().unwrap();159 let parameters = param_names_and_values160 .iter()161 .zip(params_indices)162 .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone())))163 .collect();164 commands.push(Command::new_parametrized(165 name,166 command_list[*command_index],167 parameters,168 ));169170 // Increment index, exiting loop on overflow.171 for (i, n) in index.iter_mut().zip(dimensions.iter()) {172 *i += 1;173 if *i < *n {174 continue 'outer;175 } else {176 *i = 0;177 }178 }179 break 'outer;180 }181182 Ok(commands)183 } else {184 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());185 if command_names.len() > command_strings.len() {186 return Err(OptionsError::TooManyCommandNames(command_strings.len()).into());187 }188189 let command_list = command_strings.collect::<Vec<&str>>();190 let mut commands = Vec::with_capacity(command_list.len());191 for (i, s) in command_list.iter().enumerate() {192 commands.push(Command::new(command_names.get(i).copied(), s));193 }194 Ok(commands)195 }196}197198/// Finds all the strings that appear multiple times in the input iterator, returning them in199/// sorted order. If no string appears more than once, the result is an empty vector.200fn find_dupes<'a, I: IntoIterator<Item = &'a str>>(i: I) -> Vec<&'a str> {201 let mut counts = BTreeMap::<&'a str, usize>::new();202 for s in i {203 *counts.entry(s).or_default() += 1;204 }205 counts206 .into_iter()207 .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })208 .collect()209}210211#[test]212fn test_get_shell_command_nonoverlapping() {213 let cmd = Command::new_parametrized(214 None,
23 unmodified lines
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {239 write!(f, "{}", self.get_shell_command())240 }241}242243#[test]244fn test_build_commands_cross_product() {245 use crate::app::get_arg_matches;246247 let matches = get_arg_matches(vec![248 "hyperfine",249 "-L",250 "par1",251 "a,b",252 "-L",253 "par2",254 "z,y",255 "echo {par1} {par2}",256 "printf '%s\n' {par1} {par2}",257 ]);258 let result = build_commands(&matches).unwrap();259260 // Iteration order: command list first, then parameters in listed order (here, "par1" before261 // "par2", which is distinct from their sorted order), with parameter values in listed order.262 let pv = |s: &str| ParameterValue::Text(s.to_string());263 let cmd = |cmd: usize, par1: &str, par2: &str| {264 let expression = ["echo {par1} {par2}", "printf '%s\n' {par1} {par2}"][cmd];265 let params = vec![("par1", pv(par1)), ("par2", pv(par2))];266 Command::new_parametrized(None, expression, params)267 };268 let expected = vec![269 cmd(0, "a", "z"),270 cmd(1, "a", "z"),271 cmd(0, "b", "z"),272 cmd(1, "b", "z"),273 cmd(0, "a", "y"),274 cmd(1, "a", "y"),275 cmd(0, "b", "y"),276 cmd(1, "b", "y"),277 ];278 assert_eq!(result, expected);279}280281#[test]282fn test_build_parameter_list_commands() {283 use crate::app::get_arg_matches;284285 let matches = get_arg_matches(vec![286 "hyperfine",287 "echo {foo}",288 "--parameter-list",289 "foo",290 "1,2",291 "--command-name",292 "name-{foo}",293 ]);294 let commands = build_commands(&matches).unwrap();295 assert_eq!(commands.len(), 2);296 assert_eq!(commands[0].get_name(), "name-1");297 assert_eq!(commands[1].get_name(), "name-2");298 assert_eq!(commands[0].get_shell_command(), "echo 1");299 assert_eq!(commands[1].get_shell_command(), "echo 2");300}301302#[test]303fn test_build_parameter_range_commands() {304 use crate::app::get_arg_matches;305 let matches = get_arg_matches(vec![306 "hyperfine",307 "echo {val}",308 "--parameter-scan",309 "val",310 "1",311 "2",312 "--parameter-step-size",313 "1",314 "--command-name",315 "name-{val}",316 ]);317 let commands = build_commands(&matches).unwrap();318 assert_eq!(commands.len(), 2);319 assert_eq!(commands[0].get_name(), "name-1");320 assert_eq!(commands[1].get_name(), "name-2");321 assert_eq!(commands[0].get_shell_command(), "echo 1");322 assert_eq!(commands[1].get_shell_command(), "echo 2");323}
modified:src/main.rs+1 added-203 removed
1use std::collections::BTreeMap;1use std::env;24use clap::ArgMatches;3use colored::*;45pub mod app;6pub mod benchmark;
17 unmodified lines
2425use app::get_arg_matches;26use benchmark::{mean_shell_spawning_time, run_benchmark};27use benchmark_result::BenchmarkResult;30use command::Command;31use error::OptionsError;28use command::{build_commands, Command};29use export::ExportManager;30use options::{Options, OutputStyleOption};34use parameter_range::get_parameterized_commands;35use tokenize::tokenize;36use types::ParameterValue;3132use anyhow::{bail, Result};3334pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {
90 unmodified lines
125 std::process::exit(1);126 }127 }128}135136/// Build the commands to benchmark137fn build_commands(matches: &ArgMatches) -> Result<Vec<Command>> {138 let command_names = matches.values_of("command-name");139 let command_strings = matches.values_of("command").unwrap();140141 if let Some(args) = matches.values_of("parameter-scan") {142 let step_size = matches.value_of("parameter-step-size");143 Ok(get_parameterized_commands(144 command_names,145 command_strings,146 args,147 step_size,148 )?)149 } else if let Some(args) = matches.values_of("parameter-list") {150 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());151152 let args: Vec<_> = args.collect();153 let param_names_and_values: Vec<(&str, Vec<String>)> = args154 .chunks_exact(2)155 .map(|pair| {156 let name = pair[0];157 let list_str = pair[1];158 (name, tokenize(list_str))159 })160 .collect();161 {162 let dupes = find_dupes(param_names_and_values.iter().map(|(name, _)| *name));163 if !dupes.is_empty() {164 bail!("Duplicate parameter names: {}", &dupes.join(", "));165 }166 }167 let command_list = command_strings.collect::<Vec<&str>>();168169 let dimensions: Vec<usize> = std::iter::once(command_list.len())170 .chain(171 param_names_and_values172 .iter()173 .map(|(_, values)| values.len()),174 )175 .collect();176 let param_space_size = dimensions.iter().product();177 if param_space_size == 0 {178 return Ok(Vec::new());179 }180181 // `--command-name` should appear exactly once or exactly B times,182 // where B is the total number of benchmarks.183 let command_name_count = command_names.len();184 if command_name_count > 1 && command_name_count != param_space_size {185 return Err(OptionsError::UnexpectedCommandNameCount(186 command_name_count,187 param_space_size,188 )189 .into());190 }191192 let mut i = 0;193 let mut commands = Vec::with_capacity(param_space_size);194 let mut index = vec![0usize; dimensions.len()];195 'outer: loop {196 let name = command_names197 .get(i)198 .or_else(|| command_names.get(0))199 .copied();200 i += 1;201202 let (command_index, params_indices) = index.split_first().unwrap();203 let parameters = param_names_and_values204 .iter()205 .zip(params_indices)206 .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone())))207 .collect();208 commands.push(Command::new_parametrized(209 name,210 command_list[*command_index],211 parameters,212 ));213214 // Increment index, exiting loop on overflow.215 for (i, n) in index.iter_mut().zip(dimensions.iter()) {216 *i += 1;217 if *i < *n {218 continue 'outer;219 } else {220 *i = 0;221 }222 }223 break 'outer;224 }225226 Ok(commands)227 } else {228 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());229 if command_names.len() > command_strings.len() {230 return Err(OptionsError::TooManyCommandNames(command_strings.len()).into());231 }232233 let command_list = command_strings.collect::<Vec<&str>>();234 let mut commands = Vec::with_capacity(command_list.len());235 for (i, s) in command_list.iter().enumerate() {236 commands.push(Command::new(command_names.get(i).copied(), s));237 }238 Ok(commands)239 }240}241242/// Finds all the strings that appear multiple times in the input iterator, returning them in243/// sorted order. If no string appears more than once, the result is an empty vector.244fn find_dupes<'a, I: IntoIterator<Item = &'a str>>(i: I) -> Vec<&'a str> {245 let mut counts = BTreeMap::<&'a str, usize>::new();246 for s in i {247 *counts.entry(s).or_default() += 1;248 }249 counts250 .into_iter()251 .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })252 .collect()253}254255#[test]256fn test_build_commands_cross_product() {257 let matches = get_arg_matches(vec![258 "hyperfine",259 "-L",260 "par1",261 "a,b",262 "-L",263 "par2",264 "z,y",265 "echo {par1} {par2}",266 "printf '%s\n' {par1} {par2}",267 ]);268 let result = build_commands(&matches).unwrap();269270 // Iteration order: command list first, then parameters in listed order (here, "par1" before271 // "par2", which is distinct from their sorted order), with parameter values in listed order.272 let pv = |s: &str| ParameterValue::Text(s.to_string());273 let cmd = |cmd: usize, par1: &str, par2: &str| {274 let expression = ["echo {par1} {par2}", "printf '%s\n' {par1} {par2}"][cmd];275 let params = vec![("par1", pv(par1)), ("par2", pv(par2))];276 Command::new_parametrized(None, expression, params)277 };278 let expected = vec![279 cmd(0, "a", "z"),280 cmd(1, "a", "z"),281 cmd(0, "b", "z"),282 cmd(1, "b", "z"),283 cmd(0, "a", "y"),284 cmd(1, "a", "y"),285 cmd(0, "b", "y"),286 cmd(1, "b", "y"),287 ];288 assert_eq!(result, expected);289}290291#[test]292fn test_build_parameter_list_commands() {293 let matches = get_arg_matches(vec![294 "hyperfine",295 "echo {foo}",296 "--parameter-list",297 "foo",298 "1,2",299 "--command-name",300 "name-{foo}",301 ]);302 let commands = build_commands(&matches).unwrap();303 assert_eq!(commands.len(), 2);304 assert_eq!(commands[0].get_name(), "name-1");305 assert_eq!(commands[1].get_name(), "name-2");306 assert_eq!(commands[0].get_shell_command(), "echo 1");307 assert_eq!(commands[1].get_shell_command(), "echo 2");308}309310#[test]311fn test_build_parameter_range_commands() {312 let matches = get_arg_matches(vec![313 "hyperfine",314 "echo {val}",315 "--parameter-scan",316 "val",317 "1",318 "2",319 "--parameter-step-size",320 "1",321 "--command-name",322 "name-{val}",323 ]);324 let commands = build_commands(&matches).unwrap();325 assert_eq!(commands.len(), 2);326 assert_eq!(commands[0].get_name(), "name-1");327 assert_eq!(commands[1].get_name(), "name-2");328 assert_eq!(commands[0].get_shell_command(), "echo 1");329 assert_eq!(commands[1].get_shell_command(), "echo 2");330}