Implement '--parameter-range var min max', see #19
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by sharkdp · committed by David Peter · parent 3966bf0 · Browse files · 5 files·+151 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+151 added−12 removed
- other:+151 added−12 removed
Provenance
- Commit
e862cf8- Tree
c98b566- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
3966bf0
5 files changed+151 added−12 removed
modified:src/hyperfine/benchmark.rs+11 added-7 removed
9 unmodified lines10 use hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};11 use hyperfine::timer::{TimerStart, TimerStop};12 use hyperfine::timer::wallclocktimer::WallClockTimer;13 use hyperfine::shell::execute_and_time;14-use hyperfine::types::BenchmarkResult;14+use hyperfine::types::{BenchmarkResult, Command};15 16 /// Results from timing a single shell command17 #[derive(Debug, Default, Copy, Clone)]18 pub struct TimingResult {17 unmodified lines36 }37 38 /// Run the given shell command and measure the execution time39 pub fn time_shell_command(40- shell_cmd: &str,40+ command: &Command,41 failure_action: CmdFailureAction,42 shell_spawning_time: Option<TimingResult>,43 ) -> io::Result<(TimingResult, bool)> {44 let wallclock_timer = WallClockTimer::start();45 46- let result = execute_and_time(shell_cmd)?;46+ let result = execute_and_time(&command.get_shell_command())?;47 48 let mut time_user = result.user_time;49 let mut time_system = result.system_time;50 34 unmodified lines85 let mut times_system: Vec<Second> = vec![];86 87 for _ in 0..COUNT {88 // Just run the shell without any command89- let res = time_shell_command("", CmdFailureAction::RaiseError, None);89+ let res = time_shell_command(&Command::new(""), CmdFailureAction::RaiseError, None);90 91 match res {92 Err(_) => {93 return Err(io::Error::new(21 unmodified lines115 116 /// Run the command specified by `--prepare`.117 fn run_preparation_command(command: &Option<String>) -> io::Result<TimingResult> {118 if let &Some(ref preparation_command) = command {119- let res = time_shell_command(preparation_command, CmdFailureAction::RaiseError, None);119+ let res = time_shell_command(120+ &Command::new(preparation_command),121+ CmdFailureAction::RaiseError,122+ None,123+ );124 if res.is_err() {125 return Err(io::Error::new(126 io::ErrorKind::Other,127 "The preparation command terminated with a non-zero exit code. \9 unmodified lines137 138 /// Run the benchmark for a single shell command139 pub fn run_benchmark(140 num: usize,137- cmd: &str,141+ cmd: &Command,142 shell_spawning_time: TimingResult,143 options: &HyperfineOptions,144 ) -> io::Result<BenchmarkResult> {145 println!(152 unmodified lines298 299 println!(" ");300 301 Ok(BenchmarkResult::new(298- cmd.to_string(),302+ cmd.get_shell_command(),303 t_mean,304 t_stddev,305 user_mean,306 system_mean,5 unmodified linesadded:src/hyperfine/error.rs+38 added
1+use std::num;2+use std::error::Error;3+use std::fmt;4+5+#[derive(Debug)]6+pub enum ParameterRangeError {7+ ParseIntError(num::ParseIntError),8+ EmptyRange,9+ TooLarge,10+}11+12+impl ParameterRangeError {13+ fn __description(&self) -> &str {14+ match *self {15+ ParameterRangeError::ParseIntError(ref e) => e.description(),16+ ParameterRangeError::EmptyRange => "Empty parameter range",17+ ParameterRangeError::TooLarge => "Parameter range is too large",18+ }19+ }20+}21+22+impl From<num::ParseIntError> for ParameterRangeError {23+ fn from(e: num::ParseIntError) -> ParameterRangeError {24+ ParameterRangeError::ParseIntError(e)25+ }26+}27+28+impl fmt::Display for ParameterRangeError {29+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {30+ write!(f, "{}", self.__description())31+ }32+}33+34+impl Error for ParameterRangeError {35+ fn description(&self) -> &str {36+ self.__description()37+ }38+}modified:src/hyperfine/mod.rs+1 added
5 unmodified lines6 pub mod shell;7 pub mod timer;8 pub mod types;9 pub mod warnings;10+pub mod error;modified:src/hyperfine/types.rs+45 added-2 removed
1-/// The types module contains common internal types for the application.2-///1+/// This module contains common internal types.2 3+use std::fmt;4+5 /// Type alias for unit of time6 pub type Second = f64;7 8+/// A command that should be benchmarked.9+#[derive(Debug, Clone)]10+pub struct Command<'a> {11+ /// The command that should be executed (without parameter substitution)12+ expression: &'a str,13+14+ /// A possible parameter value.15+ parameter: Option<(&'a str, i32)>,16+}17+18+impl<'a> Command<'a> {19+ pub fn new(expression: &'a str) -> Command<'a> {20+ Command {21+ expression: expression,22+ parameter: None,23+ }24+ }25+26+ pub fn new_parametrized(expression: &'a str, parameter: &'a str, value: i32) -> Command<'a> {27+ Command {28+ expression: expression,29+ parameter: Some((parameter, value)),30+ }31+ }32+33+ pub fn get_shell_command(&self) -> String {34+ match self.parameter {35+ Some((param_name, param_value)) => self.expression.replace(36+ &format!("{{{param_name}}}", param_name = param_name),37+ ¶m_value.to_string(),38+ ),39+ None => self.expression.into(),40+ }41+ }42+}43+44+impl<'a> fmt::Display for Command<'a> {45+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {46+ write!(f, "{}", self.get_shell_command())47+ }48+}49+50 /// Action to take when an executed command fails.51 #[derive(Debug, Clone, Copy, PartialEq)]52 pub enum CmdFailureAction {53 /// Exit with an error message106 unmodified linesmodified:src/main.rs+56 added-3 removed
28 unmodified lines29 30 use std::cmp;31 use std::error::Error;32 use std::io;33+use std::ops::Range;34 35 use atty::Stream;36 use colored::*;37 use clap::{App, AppSettings, Arg};38 39 mod hyperfine;40 41 use hyperfine::internal::write_benchmark_comparison;41-use hyperfine::types::{BenchmarkResult, CmdFailureAction, HyperfineOptions, OutputStyleOption};42+use hyperfine::types::{BenchmarkResult, CmdFailureAction, Command, HyperfineOptions,43+ OutputStyleOption};44 use hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};45 use hyperfine::export::{ExportManager, ExportType};46+use hyperfine::error::ParameterRangeError;47 48 /// Print error message to stderr and terminate49 pub fn error(message: &str) -> ! {50 eprintln!("{} {}", "Error:".red(), message);51 std::process::exit(1);52 }53 54 /// Runs the benchmark for the given commands52-fn run(commands: &Vec<&str>, options: &HyperfineOptions) -> io::Result<Vec<BenchmarkResult>> {55+fn run(commands: &Vec<Command>, options: &HyperfineOptions) -> io::Result<Vec<BenchmarkResult>> {56 let shell_spawning_time = mean_shell_spawning_time(&options.output_style)?;57 58 let mut timing_results = vec![];59 4 unmodified lines64 65 Ok(timing_results)66 }67 68+/// A function to read the `--parameter-range` arguments69+fn parse_parameter_range_args<'a>(70+ mut vals: clap::Values<'a>,71+) -> Result<(&'a str, Range<i32>), ParameterRangeError> {72+ let param_name = vals.next().unwrap();73+ let param_min: i32 = vals.next().unwrap().parse()?;74+ let param_max: i32 = vals.next().unwrap().parse()?;75+76+ const MAX_PARAMETERS: i32 = 100000;77+ if param_max - param_min > MAX_PARAMETERS {78+ return Err(ParameterRangeError::TooLarge);79+ }80+81+ if param_max < param_min {82+ return Err(ParameterRangeError::EmptyRange);83+ }84+85+ return Ok((param_name, param_min..(param_max + 1)));86+}87+88 fn main() {89 // Process command line options90 let mut options = HyperfineOptions::default();91 70 unmodified lines162 .short("i")163 .help("Ignore non-zero exit codes."),164 )165 .arg(166+ Arg::with_name("parameter-range")167+ .long("parameter-range")168+ .short("r")169+ .help(170+ "Perform benchmark runs for each value in the range MIN..MAX. Replaces the \171+ string '{VAR}' in each command by the current parameter value.",172+ )173+ .takes_value(true)174+ .value_names(&["VAR", "MIN", "MAX"]),175+ )176+ .arg(177 Arg::with_name("export-csv")178 .long("export-csv")179 .takes_value(true)180 .value_name("FILE")65 unmodified lines246 if matches.is_present("ignore-failure") {247 options.failure_action = CmdFailureAction::Ignore;248 }249 216- let commands = matches.values_of("command").unwrap().collect();250+ let command_strings = matches.values_of("command").unwrap();251+252+ let commands = if let Some(args) = matches.values_of("parameter-range") {253+ match parse_parameter_range_args(args) {254+ Ok((param_name, param_range)) => {255+ let mut commands = vec![];256+ let command_strings = command_strings.collect::<Vec<&str>>();257+ for value in param_range.start..param_range.end {258+ for ref cmd in &command_strings {259+ commands.push(Command::new_parametrized(cmd, param_name, value));260+ }261+ }262+ commands263+ }264+ Err(e) => error(e.description()),265+ }266+ } else {267+ command_strings.map(|c| Command::new(c)).collect()268+ };269+270 let res = run(&commands, &options);271 272 match res {273 Ok(timing_results) => {12 unmodified lines