Makes `--comand-name` take arguments from `--parameter-list`.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Steven Gu · committed by David Peter · parent a044532 · Browse files · 4 files·+185 added−37 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+185 added−37 removed
- other:+185 added−37 removed
Provenance
- Commit
538dd06- Tree
e39cf2f- Author
Steven Gu <asongala@163.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
a044532
4 files changed+185 added−37 removed
modified:src/hyperfine/benchmark.rs+5 added-12 removed
115 unmodified lines116 for _ in 0..COUNT {117 // Just run the shell without any command118 let res = time_shell_command(119 shell,120- &Command::new(""),120+ &Command::new(None, ""),121 show_output,122 CmdFailureAction::RaiseError,123 None,124 );103 unmodified lines228 cmd: &Command<'_>,229 shell_spawning_time: TimingResult,230 options: &HyperfineOptions,231 ) -> io::Result<BenchmarkResult> {232- let shell_cmd = cmd.get_shell_command();233- let command_name = if let Some(names) = &options.names {234- names.get(num).unwrap_or(&shell_cmd)235- } else {236- &shell_cmd237- };238- let command_name = command_name.to_string();239-232+ let command_name = cmd.get_name();233 if options.output_style != OutputStyleOption::Disabled {234 println!(235 "{}{}: {}",236 "Benchmark ".bold(),237 (num + 1).to_string().bold(),245- &command_name238+ command_name,239 );240 }241 242 let mut times_real: Vec<Second> = vec![];8 unmodified lines251 &values[0]252 } else {253 &values[num]254 };262- Command::new_parametrized(preparation_command, cmd.get_parameters().clone())255+ Command::new_parametrized(None, preparation_command, cmd.get_parameters().clone())256 });257 258 // Warmup phase259 if options.warmup_count > 0 {182 unmodified lines442 }443 444 // Run cleanup command445 let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {453- Command::new_parametrized(cleanup_command, cmd.get_parameters().clone())446+ Command::new_parametrized(None, cleanup_command, cmd.get_parameters().clone())447 });448 run_cleanup_command(&options.shell, &cleanup_cmd, options.show_output)?;449 450 Ok(BenchmarkResult::new(16 unmodified linesmodified:src/hyperfine/parameter_range.rs+73 added-5 removed
81 unmodified lines82 fn build_parameterized_commands<'a, T: Numeric>(83 param_min: T,84 param_max: T,85 step: T,86+ command_names: Vec<&'a str>,87 command_strings: Vec<&'a str>,88 param_name: &'a str,89 ) -> Result<Vec<Command<'a>>, ParameterScanError> {90 validate_params(param_min, param_max, step)?;91 let param_range = RangeStep::new(param_min, param_max, step);92 let mut commands = vec![];93 94+ let mut i = 0;95+ let name_count = command_names.len();96 for value in param_range {97 for cmd in &command_strings {98+ // Sets the command name by index (remainder) if exists.99+ let name = if name_count > 0 {100+ Some(command_names[i % name_count])101+ } else {102+ None103+ };104+ i += 1;105+106 commands.push(Command::new_parametrized(107+ name,108 cmd,109 vec![(param_name, ParameterValue::Numeric(value.into()))],110 ));111 }1 unmodified line113 Ok(commands)114 }115 116 pub fn get_parameterized_commands<'a>(117+ command_names: Option<Values<'a>>,118 command_strings: Values<'a>,119 mut vals: clap::Values<'a>,120 step: Option<&str>,121 ) -> Result<Vec<Command<'a>>, ParameterScanError> {122+ let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());123 let command_strings = command_strings.collect::<Vec<&str>>();124 let param_name = vals.next().unwrap();125 let param_min = vals.next().unwrap();126 let param_max = vals.next().unwrap();7 unmodified lines134 return build_parameterized_commands(135 param_min,136 param_max,137 step,138+ command_names,139 command_strings,140 param_name,141 );142 }6 unmodified lines149 return Err(ParameterScanError::StepRequired);150 }151 152 let step = Decimal::from_str(step.unwrap())?;138- build_parameterized_commands(param_min, param_max, step, command_strings, param_name)153+ build_parameterized_commands(154+ param_min,155+ param_max,156+ step,157+ command_names,158+ command_strings,159+ param_name,160+ )161 }162 163 #[test]164 fn test_integer_range() {19 unmodified lines184 185 #[test]186 fn test_get_parameterized_commands_int() {187 let commands =166- build_parameterized_commands(1i32, 7i32, 3i32, vec!["echo {val}"], "val").unwrap();188+ build_parameterized_commands(1i32, 7i32, 3i32, vec![], vec!["echo {val}"], "val").unwrap();189 assert_eq!(commands.len(), 3);190+ assert_eq!(commands[2].get_name(), "echo 7");191 assert_eq!(commands[2].get_shell_command(), "echo 7");192 }193 194 #[test]1 unmodified line196 let param_min = Decimal::from_str("0").unwrap();197 let param_max = Decimal::from_str("1").unwrap();198 let step = Decimal::from_str("0.33").unwrap();199 177- let commands =178- build_parameterized_commands(param_min, param_max, step, vec!["echo {val}"], "val")179- .unwrap();200+ let commands = build_parameterized_commands(201+ param_min,202+ param_max,203+ step,204+ vec![],205+ vec!["echo {val}"],206+ "val",207+ )208+ .unwrap();209 assert_eq!(commands.len(), 4);210+ assert_eq!(commands[3].get_name(), "echo 0.99");211 assert_eq!(commands[3].get_shell_command(), "echo 0.99");212 }213+214+#[test]215+fn test_get_parameterized_command_names() {216+ let commands = build_parameterized_commands(217+ 1i32,218+ 3i32,219+ 1i32,220+ vec!["name-{val}"],221+ vec!["echo {val}"],222+ "val",223+ )224+ .unwrap();225+ assert_eq!(commands.len(), 3);226+ let command_names = commands227+ .iter()228+ .map(|c| c.get_name())229+ .collect::<Vec<String>>();230+ assert_eq!(command_names, vec!["name-1", "name-2", "name-3"]);231+}232+233+#[test]234+fn test_get_specified_command_names() {235+ let commands = build_parameterized_commands(236+ 1i32,237+ 3i32,238+ 1i32,239+ vec!["name-a", "name-b", "name-c"],240+ vec!["echo {val}"],241+ "val",242+ )243+ .unwrap();244+ assert_eq!(commands.len(), 3);245+ let command_names = commands246+ .iter()247+ .map(|c| c.get_name())248+ .collect::<Vec<String>>();249+ assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);250+}modified:src/hyperfine/types.rs+37 added-6 removed
56 unmodified lines57 58 /// A command that should be benchmarked.59 #[derive(Debug, Clone, PartialEq, Eq)]60 pub struct Command<'a> {61+ /// The command name (without parameter substitution)62+ name: Option<&'a str>,63+64 /// The command that should be executed (without parameter substitution)65 expression: &'a str,66 67 /// Zero or more parameter values.68 parameters: Vec<(&'a str, ParameterValue)>,69 }70 71 impl<'a> Command<'a> {69- pub fn new(expression: &'a str) -> Command<'a> {72+ pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {73 Command {74+ name,75 expression,76 parameters: Vec::new(),77 }78 }79 80 pub fn new_parametrized(81+ name: Option<&'a str>,82 expression: &'a str,83 parameters: Vec<(&'a str, ParameterValue)>,84 ) -> Command<'a> {85 Command {86+ name,87 expression,88 parameters,89 }90 }91 92+ pub fn get_name(&self) -> String {93+ self.name.map_or_else(94+ || self.get_shell_command(),95+ |name| self.replace_parameters_in(name),96+ )97+ }98+99 pub fn get_shell_command(&self) -> String {100+ self.replace_parameters_in(self.expression)101+ }102+103+ pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {104+ &self.parameters105+ }106+107+ fn replace_parameters_in(&self, original: &str) -> String {108 let mut result = String::new();109 let mut replacements = BTreeMap::<String, String>::new();110 for (param_name, param_value) in &self.parameters {111 replacements.insert(112 format!("{{{param_name}}}", param_name = param_name),113 param_value.to_string(),114 );115 }95- let mut remaining = self.expression;116+ let mut remaining = original;117 // Manually replace consecutive occurrences to avoid double-replacing: e.g.,118 //119 // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'120 //10 unmodified lines131 remaining = &remaining[head.len_utf8()..];132 }133 result134 }114-115- pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {116- &self.parameters117- }135 }136 137 #[test]138 fn test_get_shell_command_nonoverlapping() {139 let cmd = Command::new_parametrized(140+ None,141 "echo {foo} {bar}",142 vec![143 ("foo", ParameterValue::Text("{bar} baz".into())),144 ("bar", ParameterValue::Text("quux".into())),1 unmodified line146 );147 assert_eq!(cmd.get_shell_command(), "echo {bar} baz quux");148 }149 150+#[test]151+fn test_get_parameterized_command_name() {152+ let cmd = Command::new_parametrized(153+ Some("name-{bar}-{foo}"),154+ "echo {foo} {bar}",155+ vec![156+ ("foo", ParameterValue::Text("baz".into())),157+ ("bar", ParameterValue::Text("quux".into())),158+ ],159+ );160+ assert_eq!(cmd.get_name(), "name-quux-baz");161+}162+163 impl<'a> fmt::Display for Command<'a> {164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {165 write!(f, "{}", self.get_shell_command())166 }173 unmodified linesmodified:src/main.rs+70 added-14 removed
72 unmodified lines73 let options = build_hyperfine_options(&matches);74 let commands = build_commands(&matches);75 let export_manager = match build_export_manager(&matches) {76 Ok(export_manager) => export_manager,77- Err(ref e) => error(&e.to_string())77+ Err(ref e) => error(&e.to_string()),78 };79 80 let res = match options {81 Ok(ref opts) => run(&commands, &opts, &export_manager),56 unmodified lines138 }139 (None, None) => {}140 };141 142- options.names = matches143- .values_of("command-name")144- .map(|values| values.map(String::from).collect::<Vec<String>>());145- if let Some(ref names) = options.names {146- let command_strings = matches.values_of("command").unwrap();147- if names.len() > command_strings.len() {148- return Err(OptionsError::TooManyCommandNames(command_strings.len()));149- }150- }151-142 options.preparation_command = matches143 .values_of("prepare")144 .map(|values| values.map(String::from).collect::<Vec<String>>());145 67 unmodified lines213 }214 215 /// Build the commands to benchmark216 fn build_commands<'a>(matches: &'a ArgMatches<'_>) -> Vec<Command<'a>> {217+ let command_names = matches.values_of("command-name");218 let command_strings = matches.values_of("command").unwrap();219 220 if let Some(args) = matches.values_of("parameter-scan") {221 let step_size = matches.value_of("parameter-step-size");231- match get_parameterized_commands(command_strings, args, step_size) {222+ match get_parameterized_commands(command_names, command_strings, args, step_size) {223 Ok(commands) => commands,224 Err(e) => error(&e.to_string()),225 }226 } else if let Some(args) = matches.values_of("parameter-list") {227+ let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());228+229 let args: Vec<_> = args.collect();230 let param_names_and_values: Vec<(&str, Vec<String>)> = args231 .chunks_exact(2)232 .map(|pair| {21 unmodified lines254 if param_space_size == 0 {255 return Vec::new();256 }257 258+ let mut i = 0;259+ let name_count = command_names.len();260 let mut commands = Vec::with_capacity(param_space_size);261 let mut index = vec![0usize; dimensions.len()];262 'outer: loop {263+ // Sets the command name by index (remainder) if exists.264+ let name = if name_count > 0 {265+ Some(command_names[i % name_count])266+ } else {267+ None268+ };269+ i += 1;270+271 let (command_index, params_indices) = index.split_first().unwrap();272 let parameters = param_names_and_values273 .iter()274 .zip(params_indices)275 .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone())))276 .collect();277 commands.push(Command::new_parametrized(278+ name,279 command_list[*command_index],280 parameters,281 ));282 10 unmodified lines293 }294 295 commands296 } else {293- command_strings.map(Command::new).collect()297+ let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());298+ if command_names.len() > command_strings.len() {299+ let err = OptionsError::TooManyCommandNames(command_strings.len());300+ error(&err.to_string());301+ }302+303+ let command_list = command_strings.collect::<Vec<&str>>();304+ let mut commands = Vec::with_capacity(command_list.len());305+ for (i, s) in command_list.iter().enumerate() {306+ commands.push(Command::new(command_names.get(i).copied(), &s));307+ }308+ commands309 }310 }311 312 /// Finds all the strings that appear multiple times in the input iterator, returning them in29 unmodified lines342 let pv = |s: &str| ParameterValue::Text(s.to_string());343 let cmd = |cmd: usize, foo: &str, bar: &str| {344 let expression = ["echo {foo} {bar}", "printf '%s\n' {foo} {bar}"][cmd];345 let params = vec![("foo", pv(foo)), ("bar", pv(bar))];331- Command::new_parametrized(expression, params)346+ Command::new_parametrized(None, expression, params)347 };348 let expected = vec![349 cmd(0, "a", "z"),350 cmd(1, "a", "z"),5 unmodified lines356 cmd(1, "b", "y"),357 ];358 assert_eq!(result, expected);359 }360+361+#[test]362+fn test_build_parameter_list_commands() {363+ let matches = get_arg_matches(vec![364+ "hyperfine",365+ "echo {foo}",366+ "--parameter-list",367+ "foo",368+ "1,2",369+ "--command-name",370+ "name-{foo}",371+ ]);372+ let commands = build_commands(&matches);373+ assert_eq!(commands.len(), 2);374+ assert_eq!(commands[0].get_name(), "name-1");375+ assert_eq!(commands[1].get_name(), "name-2");376+ assert_eq!(commands[0].get_shell_command(), "echo 1");377+ assert_eq!(commands[1].get_shell_command(), "echo 2");378+}379+380+#[test]381+fn test_build_parameter_range_commands() {382+ let matches = get_arg_matches(vec![383+ "hyperfine",384+ "echo {val}",385+ "--parameter-scan",386+ "val",387+ "1",388+ "2",389+ "--parameter-step-size",390+ "1",391+ "--command-name",392+ "name-{val}",393+ ]);394+ let commands = build_commands(&matches);395+ assert_eq!(commands.len(), 2);396+ assert_eq!(commands[0].get_name(), "name-1");397+ assert_eq!(commands[1].get_name(), "name-2");398+ assert_eq!(commands[0].get_shell_command(), "echo 1");399+ assert_eq!(commands[1].get_shell_command(), "echo 2");400+}