Skip to content
Myr

Add support for floats in --parameter-scan

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

authored by Piyush Rungta · committed by David Peter · parent 737403d · Browse files · 7 files+244 added−49 removed
This commit

State

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

Diff stats

7 files+244 added−49 removed

  • other:+244 added−49 removed

7 files+244 added−49 removed

modified:src/hyperfine/error.rs+11 added
1use rust_decimal::Error as DecimalError;2use std::error::Error;3use std::fmt;4use std::num;56#[derive(Debug)]7pub enum ParameterScanError {8 ParseIntError(num::ParseIntError),9 ParseDecimalError(DecimalError),10 EmptyRange,11 TooLarge,12 ZeroStep,13 StepRequired,14}1516impl From<num::ParseIntError> for ParameterScanError {17 fn from(e: num::ParseIntError) -> ParameterScanError {18 ParameterScanError::ParseIntError(e)19 }20}2122impl From<DecimalError> for ParameterScanError {23 fn from(e: DecimalError) -> ParameterScanError {24 ParameterScanError::ParseDecimalError(e)25 }26}2728impl fmt::Display for ParameterScanError {29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {30 write!(f, "{}", self.description())31 }
2 unmodified lines
34impl Error for ParameterScanError {35 fn description(&self) -> &str {36 match *self {37 ParameterScanError::ParseIntError(ref e) => e.description(),38 ParameterScanError::ParseDecimalError(ref e) => e.description(),39 ParameterScanError::EmptyRange => "Empty parameter range",40 ParameterScanError::TooLarge => "Parameter range is too large",41 ParameterScanError::ZeroStep => "Zero is not a valid parameter step",42 ParameterScanError::StepRequired => "Step is required when range bounds are floats",43 }44 }45}46
20 unmodified lines
modified:src/hyperfine/mod.rs+1 added
3 unmodified lines
4pub mod export;5pub mod format;6pub mod internal;7pub mod outlier_detection;8pub mod parameter_range;9pub mod shell;10pub mod timer;11pub mod types;12pub mod units;
1 unmodified line
added:src/hyperfine/parameter_range.rs+176 added
1use crate::hyperfine::error::ParameterScanError;2use crate::hyperfine::types::{Command, NumericType};3use clap::Values;4use rust_decimal::Decimal;5use std::ops::{Add, AddAssign, Div, Sub};6use std::str::FromStr;78trait Numeric:9 Add<Output = Self>10 + Sub<Output = Self>11 + Div<Output = Self>12 + AddAssign13 + PartialOrd14 + Copy15 + Clone16 + From<i32>17 + Into<NumericType>18{19}20impl<21 T: Add<Output = Self>22 + Sub<Output = Self>23 + Div<Output = Self>24 + AddAssign25 + PartialOrd26 + Copy27 + Clone28 + From<i32>29 + Into<NumericType>,30 > Numeric for T31{32}3334struct RangeStep<T> {35 state: T,36 end: T,37 step: T,38}3940impl<T: Numeric> RangeStep<T> {41 fn new(start: T, end: T, step: T) -> RangeStep<T> {42 RangeStep {43 state: start,44 end,45 step,46 }47 }48}4950impl<T: Numeric> Iterator for RangeStep<T> {51 type Item = T;5253 fn next(&mut self) -> Option<Self::Item> {54 if self.state > self.end {55 return None;56 }57 let return_val = self.state;58 self.state += self.step;5960 Some(return_val)61 }62}6364fn validate_params<T: Numeric>(start: T, end: T, step: T) -> Result<(), ParameterScanError> {65 if end < start {66 return Err(ParameterScanError::EmptyRange);67 }6869 if step == T::from(0) {70 return Err(ParameterScanError::ZeroStep);71 }7273 const MAX_PARAMETERS: i32 = 100_000;74 let steps = (end - start + T::from(1)) / step;75 if steps > T::from(MAX_PARAMETERS) {76 return Err(ParameterScanError::TooLarge);77 }7879 Ok(())80}8182fn build_parameterized_commands<'a, T: Numeric>(83 param_min: T,84 param_max: T,85 step: T,86 command_strings: Vec<&'a str>,87 param_name: &'a str,88) -> Result<Vec<Command<'a>>, ParameterScanError> {89 validate_params(param_min, param_max, step)?;90 let param_range = RangeStep::new(param_min, param_max, step);91 let mut commands = vec![];9293 for value in param_range {94 for cmd in &command_strings {95 commands.push(Command::new_parametrized(cmd, param_name, value.into()));96 }97 }98 Ok(commands)99}100101pub fn get_parameterized_commands<'a>(102 command_strings: Values<'a>,103 mut vals: clap::Values<'a>,104 step: Option<&str>,105) -> Result<Vec<Command<'a>>, ParameterScanError> {106 let command_strings = command_strings.collect::<Vec<&str>>();107 let param_name = vals.next().unwrap();108 let param_min = vals.next().unwrap();109 let param_max = vals.next().unwrap();110111 // attempt to parse as integers112 if let (Ok(param_min), Ok(param_max)) = (param_min.parse::<i32>(), param_max.parse::<i32>()) {113 let step = step.unwrap_or("1").parse::<i32>()?;114 return build_parameterized_commands(115 param_min,116 param_max,117 step,118 command_strings,119 param_name,120 );121 }122123 // try parsing them as decimals124 let param_min = Decimal::from_str(param_min)?;125 let param_max = Decimal::from_str(param_max)?;126127 if step.is_none() {128 return Err(ParameterScanError::StepRequired);129 }130131 let step = Decimal::from_str(step.unwrap())?;132 build_parameterized_commands(param_min, param_max, step, command_strings, param_name)133}134135#[test]136fn test_integer_range() {137 let param_range: Vec<i32> = RangeStep::new(0, 10, 3).collect();138139 assert_eq!(param_range.len(), 4);140 assert_eq!(param_range[0], 0);141 assert_eq!(param_range[3], 9);142}143144#[test]145fn test_decimal_range() {146 let param_min = Decimal::from(0);147 let param_max = Decimal::from(1);148 let step = Decimal::from_str("0.1").unwrap();149150 let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step).collect();151152 assert_eq!(param_range.len(), 11);153 assert_eq!(param_range[0], Decimal::from(0));154 assert_eq!(param_range[10], Decimal::from(1));155}156157#[test]158fn test_get_parameterized_commands_int() {159 let commands =160 build_parameterized_commands(1i32, 7i32, 3i32, vec!["echo {val}"], "val").unwrap();161 assert_eq!(commands.len(), 3);162 assert_eq!(commands[2].get_shell_command(), "echo 7");163}164165#[test]166fn test_get_parameterized_commands_decimal() {167 let param_min = Decimal::from_str("0").unwrap();168 let param_max = Decimal::from_str("1").unwrap();169 let step = Decimal::from_str("0.33").unwrap();170171 let commands =172 build_parameterized_commands(param_min, param_max, step, vec!["echo {val}"], "val")173 .unwrap();174 assert_eq!(commands.len(), 4);175 assert_eq!(commands[3].get_shell_command(), "echo 0.99");176}
modified:src/hyperfine/types.rs+38 added-5 removed
1use rust_decimal::Decimal;2/// This module contains common internal types.3use serde::*;4use std::fmt;5
4 unmodified lines
1011#[cfg(windows)]12pub const DEFAULT_SHELL: &str = "cmd.exe";1314#[derive(Debug, Clone, Serialize, Copy)]15#[serde(untagged)]16pub enum NumericType {17 Int(i32),18 Decimal(Decimal),19}2021impl fmt::Display for NumericType {22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {23 match *self {24 NumericType::Int(i) => fmt::Display::fmt(&i, f),25 NumericType::Decimal(i) => fmt::Display::fmt(&i, f),26 }27 }28}2930impl Into<NumericType> for i32 {31 fn into(self) -> NumericType {32 NumericType::Int(self)33 }34}3536impl Into<NumericType> for Decimal {37 fn into(self) -> NumericType {38 NumericType::Decimal(self)39 }40}4142/// A command that should be benchmarked.43#[derive(Debug, Clone)]44pub struct Command<'a> {45 /// The command that should be executed (without parameter substitution)46 expression: &'a str,4748 /// A possible parameter value.20 parameter: Option<(&'a str, i32)>,49 parameter: Option<(&'a str, NumericType)>,50}5152impl<'a> Command<'a> {53 pub fn new(expression: &'a str) -> Command<'a> {
2 unmodified lines
56 parameter: None,57 }58 }5931 pub fn new_parametrized(expression: &'a str, parameter: &'a str, value: i32) -> Command<'a> {60 pub fn new_parametrized(61 expression: &'a str,62 parameter: &'a str,63 value: NumericType,64 ) -> Command<'a> {65 Command {66 expression,67 parameter: Some((parameter, value)),68 }
8 unmodified lines
77 None => self.expression.into(),78 }79 }8048 pub fn get_parameter(&self) -> Option<(&'a str, i32)> {81 pub fn get_parameter(&self) -> Option<(&'a str, NumericType)> {82 self.parameter83 }84}85
126 unmodified lines
212 pub times: Option<Vec<Second>>,213214 /// Any parameter used215 #[serde(skip_serializing_if = "Option::is_none")]183 pub parameter: Option<i32>,216 pub parameter: Option<NumericType>,217}218219impl BenchmarkResult {220 /// Create a new entry with the given values.
6 unmodified lines
227 system: Second,228 min: Second,229 max: Second,230 times: Vec<Second>,198 parameter: Option<i32>,231 parameter: Option<NumericType>,232 ) -> Self {233 BenchmarkResult {234 command,235 mean,
11 unmodified lines
modified:src/main.rs+5 added-44 removed
1use std::cmp;2use std::env;3use std::error::Error;4use std::io;5use std::iter::StepBy;6use std::ops::Range;56use atty::Stream;7use clap::ArgMatches;8use colored::*;
1 unmodified line
10mod hyperfine;1112use crate::hyperfine::app::get_arg_matches;13use crate::hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};16use crate::hyperfine::error::{OptionsError, ParameterScanError};14use crate::hyperfine::error::OptionsError;15use crate::hyperfine::export::{ExportManager, ExportType};16use crate::hyperfine::internal::write_benchmark_comparison;17use crate::hyperfine::parameter_range::get_parameterized_commands;18use crate::hyperfine::types::{19 BenchmarkResult, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption,20};21use crate::hyperfine::units::Unit;
18 unmodified lines
4041 Ok(timing_results)42}4345/// A function to read the `--parameter-scan` arguments46fn parse_parameter_scan_args<'a>(47 mut vals: clap::Values<'a>,48 step_size: &str,49) -> Result<(&'a str, StepBy<Range<i32>>), ParameterScanError> {50 let param_name = vals.next().unwrap();51 let param_min: i32 = vals.next().unwrap().parse()?;52 let param_max: i32 = vals.next().unwrap().parse()?;53 let step_size = step_size.parse()?;5455 const MAX_PARAMETERS: i32 = 100_000;56 if param_max - param_min > MAX_PARAMETERS {57 return Err(ParameterScanError::TooLarge);58 }5960 if param_max < param_min {61 return Err(ParameterScanError::EmptyRange);62 }6364 if step_size == 0 {65 // Iterator::step_by panics for zero step66 return Err(ParameterScanError::ZeroStep);67 }6869 let param_range = (param_min..(param_max + 1)).step_by(step_size);7071 Ok((param_name, param_range))72}7344fn main() {45 let matches = get_arg_matches(env::args_os());46 let options = build_hyperfine_options(&matches);47 let export_manager = build_export_manager(&matches);
137 unmodified lines
185fn build_commands<'a>(matches: &'a ArgMatches<'_>) -> Vec<Command<'a>> {186 let command_strings = matches.values_of("command").unwrap();187188 if let Some(args) = matches.values_of("parameter-scan") {219 let step_size = matches.value_of("parameter-step-size").unwrap_or("1");220 match parse_parameter_scan_args(args, step_size) {221 Ok((param_name, param_range)) => {222 let mut commands = vec![];223 let command_strings = command_strings.collect::<Vec<&str>>();224 for value in param_range {225 for cmd in &command_strings {226 commands.push(Command::new_parametrized(cmd, param_name, value));227 }228 }229 commands230 }189 let step_size = matches.value_of("parameter-step-size");190 match get_parameterized_commands(command_strings, args, step_size) {191 Ok(commands) => commands,192 Err(e) => error(e.description()),193 }194 } else {195 command_strings.map(Command::new).collect()
2 unmodified lines
modified:Cargo.lock+12 added
178 unmodified lines
179 "colored 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)",180 "csv 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)",181 "indicatif 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",182 "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)",183 "rust_decimal 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)",184 "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)",185 "serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)",186 "statistical 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",187 "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
329 unmodified lines
517version = "0.8.13"518source = "registry+https://github.com/rust-lang/crates.io-index"519520[[package]]521name = "rust_decimal"522version = "1.0.3"523source = "registry+https://github.com/rust-lang/crates.io-index"524dependencies = [525 "byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)",526 "num 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",527 "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)",528]529530[[package]]531name = "rustc_version"532version = "0.2.3"533source = "registry+https://github.com/rust-lang/crates.io-index"534dependencies = [
232 unmodified lines
767"checksum regex 1.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "8f0a0bcab2fd7d1d7c54fa9eae6f43eddeb9ce2e7352f8518a814a4f65d60c58"768"checksum regex-automata 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "3ed09217220c272b29ef237a974ad58515bde75f194e3ffa7e6d0bf0f3b01f86"769"checksum regex-syntax 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)" = "dcfd8681eebe297b81d98498869d4aae052137651ad7b96822f09ceb690d0a96"770"checksum rgb 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)" = "4f089652ca87f5a82a62935ec6172a534066c7b97be003cc8f702ee9a7a59c92"771"checksum rust_decimal 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "f7a28ded8f10361cefb69a8d8e1d195acf59344150534c165c401d6611cf013d"772"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"773"checksum ryu 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c92464b447c0ee8c4fb3824ecc8383b81717b9f1e74ba2e72540aef7b9f82997"774"checksum scopeguard 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b42e15e59b18a828bbf5c58ea01debb36b9b096346de35d941dcb89009f24a0d"775"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"
22 unmodified lines
modified:Cargo.toml+1 added