Skip to content
Myr

Introduce Commands struct

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 c5a2266 · Browse files · 4 files+133 added−119 removed
This commit

State

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

Diff stats

4 files+133 added−119 removed

  • other:+133 added−119 removed

4 files+133 added−119 removed

modified:src/benchmark/schedule.rs+3 added-2 removed
1use crate::command::Commands;2use crate::export::ExportManager;3use crate::options::{Options, OutputStyleOption};2use crate::{command::Command, export::ExportManager};45use super::{mean_shell_spawning_time, relative_speed, result::BenchmarkResult, run_benchmark};67use anyhow::{bail, Result};
37 unmodified lines
45 }46}4748pub fn run_benchmarks_and_print_comparison(48 commands: &[Command<'_>],49 commands: &Commands,50 options: &Options,51 export_manager: &ExportManager,52) -> Result<()> {53 let shell_spawning_time =
28 unmodified lines
modified:src/app.rs+1 added-1 removed
1use std::ffi::OsString;23use clap::{crate_version, App, AppSettings, Arg, ArgMatches};45pub fn get_arg_matches<'a, I, T>(args: I) -> ArgMatches5pub fn get_cli_arguments<'a, I, T>(args: I) -> ArgMatches6where7 I: IntoIterator<Item = T>,8 T: Into<OsString> + Clone + 'a,9{
248 unmodified lines
modified:src/command.rs+123 added-110 removed
88 unmodified lines
89 result90 }91}9293/// Build the commands to benchmark94pub fn build_commands(matches: &ArgMatches) -> Result<Vec<Command>> {95 let command_names = matches.values_of("command-name");96 let command_strings = matches.values_of("command").unwrap();93/// Finds all the strings that appear multiple times in the input iterator, returning them in94/// sorted order. If no string appears more than once, the result is an empty vector.95fn find_duplicates<'a, I: IntoIterator<Item = &'a str>>(i: I) -> Vec<&'a str> {96 let mut counts = BTreeMap::<&'a str, usize>::new();97 for s in i {98 *counts.entry(s).or_default() += 1;99 }100 counts101 .into_iter()102 .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })103 .collect()104}10598 if let Some(args) = matches.values_of("parameter-scan") {99 let step_size = matches.value_of("parameter-step-size");100 Ok(get_parameterized_commands(101 command_names,102 command_strings,103 args,104 step_size,105 )?)106 } else if let Some(args) = matches.values_of("parameter-list") {107 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());106pub struct Commands<'a>(Vec<Command<'a>>);107108impl<'a> Commands<'a> {109 /// Build the commands to benchmark110 pub fn from_cli_arguments(matches: &'a ArgMatches) -> Result<Commands> {111 let command_names = matches.values_of("command-name");112 let command_strings = matches.values_of("command").unwrap();113114 if let Some(args) = matches.values_of("parameter-scan") {115 let step_size = matches.value_of("parameter-step-size");116 Ok(Self(get_parameterized_commands(117 command_names,118 command_strings,119 args,120 step_size,121 )?))122 } else if let Some(args) = matches.values_of("parameter-list") {123 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());124109 let args: Vec<_> = args.collect();110 let param_names_and_values: Vec<(&str, Vec<String>)> = args111 .chunks_exact(2)112 .map(|pair| {113 let name = pair[0];114 let list_str = pair[1];115 (name, tokenize(list_str))116 })117 .collect();118 {119 let dupes = find_dupes(param_names_and_values.iter().map(|(name, _)| *name));120 if !dupes.is_empty() {121 bail!("Duplicate parameter names: {}", &dupes.join(", "));125 let args: Vec<_> = args.collect();126 let param_names_and_values: Vec<(&str, Vec<String>)> = args127 .chunks_exact(2)128 .map(|pair| {129 let name = pair[0];130 let list_str = pair[1];131 (name, tokenize(list_str))132 })133 .collect();134 {135 let duplicates =136 find_duplicates(param_names_and_values.iter().map(|(name, _)| *name));137 if !duplicates.is_empty() {138 bail!("Duplicate parameter names: {}", &duplicates.join(", "));139 }140 }123 }124 let command_list = command_strings.collect::<Vec<&str>>();141 let command_list = command_strings.collect::<Vec<&str>>();142126 let dimensions: Vec<usize> = std::iter::once(command_list.len())127 .chain(128 param_names_and_values129 .iter()130 .map(|(_, values)| values.len()),131 )132 .collect();133 let param_space_size = dimensions.iter().product();134 if param_space_size == 0 {135 return Ok(Vec::new());136 }143 let dimensions: Vec<usize> = std::iter::once(command_list.len())144 .chain(145 param_names_and_values146 .iter()147 .map(|(_, values)| values.len()),148 )149 .collect();150 let param_space_size = dimensions.iter().product();151 if param_space_size == 0 {152 return Ok(Self(Vec::new()));153 }154138 // `--command-name` should appear exactly once or exactly B times,139 // where B is the total number of benchmarks.140 let command_name_count = command_names.len();141 if command_name_count > 1 && command_name_count != param_space_size {142 return Err(OptionsError::UnexpectedCommandNameCount(143 command_name_count,144 param_space_size,145 )146 .into());147 }155 // `--command-name` should appear exactly once or exactly B times,156 // where B is the total number of benchmarks.157 let command_name_count = command_names.len();158 if command_name_count > 1 && command_name_count != param_space_size {159 return Err(OptionsError::UnexpectedCommandNameCount(160 command_name_count,161 param_space_size,162 )163 .into());164 }165149 let mut i = 0;150 let mut commands = Vec::with_capacity(param_space_size);151 let mut index = vec![0usize; dimensions.len()];152 'outer: loop {153 let name = command_names154 .get(i)155 .or_else(|| command_names.get(0))156 .copied();157 i += 1;166 let mut i = 0;167 let mut commands = Vec::with_capacity(param_space_size);168 let mut index = vec![0usize; dimensions.len()];169 'outer: loop {170 let name = command_names171 .get(i)172 .or_else(|| command_names.get(0))173 .copied();174 i += 1;175159 let (command_index, params_indices) = index.split_first().unwrap();160 let parameters = param_names_and_values161 .iter()162 .zip(params_indices)163 .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone())))164 .collect();165 commands.push(Command::new_parametrized(166 name,167 command_list[*command_index],168 parameters,169 ));176 let (command_index, params_indices) = index.split_first().unwrap();177 let parameters = param_names_and_values178 .iter()179 .zip(params_indices)180 .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone())))181 .collect();182 commands.push(Command::new_parametrized(183 name,184 command_list[*command_index],185 parameters,186 ));187171 // Increment index, exiting loop on overflow.172 for (i, n) in index.iter_mut().zip(dimensions.iter()) {173 *i += 1;174 if *i < *n {175 continue 'outer;176 } else {177 *i = 0;188 // Increment index, exiting loop on overflow.189 for (i, n) in index.iter_mut().zip(dimensions.iter()) {190 *i += 1;191 if *i < *n {192 continue 'outer;193 } else {194 *i = 0;195 }196 }197 break 'outer;198 }180 break 'outer;181 }199183 Ok(commands)184 } else {185 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());186 if command_names.len() > command_strings.len() {187 return Err(OptionsError::TooManyCommandNames(command_strings.len()).into());188 }200 Ok(Self(commands))201 } else {202 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());203 if command_names.len() > command_strings.len() {204 return Err(OptionsError::TooManyCommandNames(command_strings.len()).into());205 }206190 let command_list = command_strings.collect::<Vec<&str>>();191 let mut commands = Vec::with_capacity(command_list.len());192 for (i, s) in command_list.iter().enumerate() {193 commands.push(Command::new(command_names.get(i).copied(), s));207 let command_list = command_strings.collect::<Vec<&str>>();208 let mut commands = Vec::with_capacity(command_list.len());209 for (i, s) in command_list.iter().enumerate() {210 commands.push(Command::new(command_names.get(i).copied(), s));211 }212 Ok(Self(commands))213 }195 Ok(commands)214 }197}215199/// Finds all the strings that appear multiple times in the input iterator, returning them in200/// sorted order. If no string appears more than once, the result is an empty vector.201fn find_dupes<'a, I: IntoIterator<Item = &'a str>>(i: I) -> Vec<&'a str> {202 let mut counts = BTreeMap::<&'a str, usize>::new();203 for s in i {204 *counts.entry(s).or_default() += 1;216 pub fn iter(&self) -> impl Iterator<Item = &Command<'a>> {217 self.0.iter()218 }206 counts207 .into_iter()208 .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })209 .collect()219220 pub fn len(&self) -> usize {221 self.0.len()222 }223}224225#[test]226fn test_get_shell_command_nonoverlapping() {
28 unmodified lines
255}256257#[test]258fn test_build_commands_cross_product() {246 use crate::app::get_arg_matches;259 use crate::app::get_cli_arguments;260248 let matches = get_arg_matches(vec![261 let matches = get_cli_arguments(vec![262 "hyperfine",263 "-L",264 "par1",265 "a,b",
2 unmodified lines
268 "z,y",269 "echo {par1} {par2}",270 "printf '%s\n' {par1} {par2}",271 ]);259 let result = build_commands(&matches).unwrap();272 let result = Commands::from_cli_arguments(&matches).unwrap().0;273274 // Iteration order: command list first, then parameters in listed order (here, "par1" before275 // "par2", which is distinct from their sorted order), with parameter values in listed order.276 let pv = |s: &str| ParameterValue::Text(s.to_string());
16 unmodified lines
293}294295#[test]296fn test_build_parameter_list_commands() {284 use crate::app::get_arg_matches;297 use crate::app::get_cli_arguments;298286 let matches = get_arg_matches(vec![299 let matches = get_cli_arguments(vec![300 "hyperfine",301 "echo {foo}",302 "--parameter-list",303 "foo",304 "1,2",305 "--command-name",306 "name-{foo}",307 ]);295 let commands = build_commands(&matches).unwrap();308 let commands = Commands::from_cli_arguments(&matches).unwrap().0;309 assert_eq!(commands.len(), 2);310 assert_eq!(commands[0].get_name(), "name-1");311 assert_eq!(commands[1].get_name(), "name-2");312 assert_eq!(commands[0].get_shell_command(), "echo 1");
1 unmodified line
314}315316#[test]317fn test_build_parameter_range_commands() {305 use crate::app::get_arg_matches;306 let matches = get_arg_matches(vec![318 use crate::app::get_cli_arguments;319 let matches = get_cli_arguments(vec![320 "hyperfine",321 "echo {val}",322 "--parameter-scan",323 "val",
3 unmodified lines
327 "1",328 "--command-name",329 "name-{val}",330 ]);318 let commands = build_commands(&matches).unwrap();331 let commands = Commands::from_cli_arguments(&matches).unwrap().0;332 assert_eq!(commands.len(), 2);333 assert_eq!(commands[0].get_name(), "name-1");334 assert_eq!(commands[1].get_name(), "name-2");335 assert_eq!(commands[0].get_shell_command(), "echo 1");
2 unmodified lines
modified:src/main.rs+6 added-6 removed
1use std::env;23use app::get_arg_matches;3use app::get_cli_arguments;4use benchmark::schedule::run_benchmarks_and_print_comparison;5use command::build_commands;5use command::Commands;6use export::ExportManager;7use options::Options;89use anyhow::Result;
16 unmodified lines
26 // Enabled ANSI colors on Windows 1027 #[cfg(windows)]28 colored::control::set_virtual_terminal(true).unwrap();2930 let matches = get_arg_matches(env::args_os());31 let options = Options::from_cli_arguments(&matches)?;32 let commands = build_commands(&matches)?;33 let export_manager = ExportManager::from_cli_arguments(&matches)?;30 let cli_arguments = get_cli_arguments(env::args_os());31 let options = Options::from_cli_arguments(&cli_arguments)?;32 let commands = Commands::from_cli_arguments(&cli_arguments)?;33 let export_manager = ExportManager::from_cli_arguments(&cli_arguments)?;3435 run_benchmarks_and_print_comparison(&commands, &options, &export_manager)36}37
9 unmodified lines