Skip to content
Myr

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

5 files+151 added−12 removed

modified:src/hyperfine/benchmark.rs+11 added-7 removed
9 unmodified lines
10use hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};11use hyperfine::timer::{TimerStart, TimerStop};12use hyperfine::timer::wallclocktimer::WallClockTimer;13use hyperfine::shell::execute_and_time;14use hyperfine::types::BenchmarkResult;14use hyperfine::types::{BenchmarkResult, Command};1516/// Results from timing a single shell command17#[derive(Debug, Default, Copy, Clone)]18pub struct TimingResult {
17 unmodified lines
36}3738/// Run the given shell command and measure the execution time39pub 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();4546 let result = execute_and_time(shell_cmd)?;46 let result = execute_and_time(&command.get_shell_command())?;4748 let mut time_user = result.user_time;49 let mut time_system = result.system_time;50
34 unmodified lines
85 let mut times_system: Vec<Second> = vec![];8687 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);9091 match res {92 Err(_) => {93 return Err(io::Error::new(
21 unmodified lines
115116/// Run the command specified by `--prepare`.117fn 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 lines
137138/// Run the benchmark for a single shell command139pub 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 lines
298299 println!(" ");300301 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 lines
added:src/hyperfine/error.rs+38 added
1use std::num;2use std::error::Error;3use std::fmt;45#[derive(Debug)]6pub enum ParameterRangeError {7 ParseIntError(num::ParseIntError),8 EmptyRange,9 TooLarge,10}1112impl 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}2122impl From<num::ParseIntError> for ParameterRangeError {23 fn from(e: num::ParseIntError) -> ParameterRangeError {24 ParameterRangeError::ParseIntError(e)25 }26}2728impl fmt::Display for ParameterRangeError {29 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {30 write!(f, "{}", self.__description())31 }32}3334impl Error for ParameterRangeError {35 fn description(&self) -> &str {36 self.__description()37 }38}
modified:src/hyperfine/mod.rs+1 added
5 unmodified lines
6pub mod shell;7pub mod timer;8pub mod types;9pub mod warnings;10pub 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.23use std::fmt;45/// Type alias for unit of time6pub type Second = f64;78/// A command that should be benchmarked.9#[derive(Debug, Clone)]10pub struct Command<'a> {11 /// The command that should be executed (without parameter substitution)12 expression: &'a str,1314 /// A possible parameter value.15 parameter: Option<(&'a str, i32)>,16}1718impl<'a> Command<'a> {19 pub fn new(expression: &'a str) -> Command<'a> {20 Command {21 expression: expression,22 parameter: None,23 }24 }2526 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 }3233 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 &param_value.to_string(),38 ),39 None => self.expression.into(),40 }41 }42}4344impl<'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}4950/// Action to take when an executed command fails.51#[derive(Debug, Clone, Copy, PartialEq)]52pub enum CmdFailureAction {53 /// Exit with an error message
106 unmodified lines
modified:src/main.rs+56 added-3 removed
28 unmodified lines
2930use std::cmp;31use std::error::Error;32use std::io;33use std::ops::Range;3435use atty::Stream;36use colored::*;37use clap::{App, AppSettings, Arg};3839mod hyperfine;4041use hyperfine::internal::write_benchmark_comparison;41use hyperfine::types::{BenchmarkResult, CmdFailureAction, HyperfineOptions, OutputStyleOption};42use hyperfine::types::{BenchmarkResult, CmdFailureAction, Command, HyperfineOptions,43 OutputStyleOption};44use hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};45use hyperfine::export::{ExportManager, ExportType};46use hyperfine::error::ParameterRangeError;4748/// Print error message to stderr and terminate49pub fn error(message: &str) -> ! {50 eprintln!("{} {}", "Error:".red(), message);51 std::process::exit(1);52}5354/// Runs the benchmark for the given commands52fn run(commands: &Vec<&str>, options: &HyperfineOptions) -> io::Result<Vec<BenchmarkResult>> {55fn run(commands: &Vec<Command>, options: &HyperfineOptions) -> io::Result<Vec<BenchmarkResult>> {56 let shell_spawning_time = mean_shell_spawning_time(&options.output_style)?;5758 let mut timing_results = vec![];59
4 unmodified lines
6465 Ok(timing_results)66}6768/// A function to read the `--parameter-range` arguments69fn 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()?;7576 const MAX_PARAMETERS: i32 = 100000;77 if param_max - param_min > MAX_PARAMETERS {78 return Err(ParameterRangeError::TooLarge);79 }8081 if param_max < param_min {82 return Err(ParameterRangeError::EmptyRange);83 }8485 return Ok((param_name, param_min..(param_max + 1)));86}8788fn main() {89 // Process command line options90 let mut options = HyperfineOptions::default();91
70 unmodified lines
162 .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 lines
246 if matches.is_present("ignore-failure") {247 options.failure_action = CmdFailureAction::Ignore;248 }249216 let commands = matches.values_of("command").unwrap().collect();250 let command_strings = matches.values_of("command").unwrap();251252 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 };269270 let res = run(&commands, &options);271272 match res {273 Ok(timing_results) => {
12 unmodified lines