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
Provenance
- Commit
b10b93f- Tree
b251e29- Author
Piyush Rungta <piyushrungta25@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
737403d
7 files changed+244 added−49 removed
modified:src/hyperfine/error.rs+11 added
1+use rust_decimal::Error as DecimalError;2 use std::error::Error;3 use std::fmt;4 use std::num;5 6 #[derive(Debug)]7 pub enum ParameterScanError {8 ParseIntError(num::ParseIntError),9+ ParseDecimalError(DecimalError),10 EmptyRange,11 TooLarge,12 ZeroStep,13+ StepRequired,14 }15 16 impl From<num::ParseIntError> for ParameterScanError {17 fn from(e: num::ParseIntError) -> ParameterScanError {18 ParameterScanError::ParseIntError(e)19 }20 }21 22+impl From<DecimalError> for ParameterScanError {23+ fn from(e: DecimalError) -> ParameterScanError {24+ ParameterScanError::ParseDecimalError(e)25+ }26+}27+28 impl fmt::Display for ParameterScanError {29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {30 write!(f, "{}", self.description())31 }2 unmodified lines34 impl 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 linesmodified:src/hyperfine/mod.rs+1 added
3 unmodified lines4 pub mod export;5 pub mod format;6 pub mod internal;7 pub mod outlier_detection;8+pub mod parameter_range;9 pub mod shell;10 pub mod timer;11 pub mod types;12 pub mod units;1 unmodified lineadded:src/hyperfine/parameter_range.rs+176 added
1+use crate::hyperfine::error::ParameterScanError;2+use crate::hyperfine::types::{Command, NumericType};3+use clap::Values;4+use rust_decimal::Decimal;5+use std::ops::{Add, AddAssign, Div, Sub};6+use std::str::FromStr;7+8+trait 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+}20+impl<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+}33+34+struct RangeStep<T> {35+ state: T,36+ end: T,37+ step: T,38+}39+40+impl<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+}49+50+impl<T: Numeric> Iterator for RangeStep<T> {51+ type Item = T;52+53+ 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;59+60+ Some(return_val)61+ }62+}63+64+fn validate_params<T: Numeric>(start: T, end: T, step: T) -> Result<(), ParameterScanError> {65+ if end < start {66+ return Err(ParameterScanError::EmptyRange);67+ }68+69+ if step == T::from(0) {70+ return Err(ParameterScanError::ZeroStep);71+ }72+73+ 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+ }78+79+ Ok(())80+}81+82+fn 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![];92+93+ 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+}100+101+pub 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();110+111+ // 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+ }122+123+ // try parsing them as decimals124+ let param_min = Decimal::from_str(param_min)?;125+ let param_max = Decimal::from_str(param_max)?;126+127+ if step.is_none() {128+ return Err(ParameterScanError::StepRequired);129+ }130+131+ let step = Decimal::from_str(step.unwrap())?;132+ build_parameterized_commands(param_min, param_max, step, command_strings, param_name)133+}134+135+#[test]136+fn test_integer_range() {137+ let param_range: Vec<i32> = RangeStep::new(0, 10, 3).collect();138+139+ assert_eq!(param_range.len(), 4);140+ assert_eq!(param_range[0], 0);141+ assert_eq!(param_range[3], 9);142+}143+144+#[test]145+fn 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();149+150+ let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step).collect();151+152+ 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+}156+157+#[test]158+fn 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+}164+165+#[test]166+fn 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();170+171+ 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
1+use rust_decimal::Decimal;2 /// This module contains common internal types.3 use serde::*;4 use std::fmt;5 4 unmodified lines10 11 #[cfg(windows)]12 pub const DEFAULT_SHELL: &str = "cmd.exe";13 14+#[derive(Debug, Clone, Serialize, Copy)]15+#[serde(untagged)]16+pub enum NumericType {17+ Int(i32),18+ Decimal(Decimal),19+}20+21+impl 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+}29+30+impl Into<NumericType> for i32 {31+ fn into(self) -> NumericType {32+ NumericType::Int(self)33+ }34+}35+36+impl Into<NumericType> for Decimal {37+ fn into(self) -> NumericType {38+ NumericType::Decimal(self)39+ }40+}41+42 /// A command that should be benchmarked.43 #[derive(Debug, Clone)]44 pub struct Command<'a> {45 /// The command that should be executed (without parameter substitution)46 expression: &'a str,47 48 /// A possible parameter value.20- parameter: Option<(&'a str, i32)>,49+ parameter: Option<(&'a str, NumericType)>,50 }51 52 impl<'a> Command<'a> {53 pub fn new(expression: &'a str) -> Command<'a> {2 unmodified lines56 parameter: None,57 }58 }59 31- 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 lines77 None => self.expression.into(),78 }79 }80 48- 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 lines212 pub times: Option<Vec<Second>>,213 214 /// Any parameter used215 #[serde(skip_serializing_if = "Option::is_none")]183- pub parameter: Option<i32>,216+ pub parameter: Option<NumericType>,217 }218 219 impl BenchmarkResult {220 /// Create a new entry with the given values.6 unmodified lines227 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 linesmodified:src/main.rs+5 added-44 removed
1 use std::cmp;2 use std::env;3 use std::error::Error;4 use std::io;5-use std::iter::StepBy;6-use std::ops::Range;5 6 use atty::Stream;7 use clap::ArgMatches;8 use colored::*;1 unmodified line10 mod hyperfine;11 12 use crate::hyperfine::app::get_arg_matches;13 use crate::hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};16-use crate::hyperfine::error::{OptionsError, ParameterScanError};14+use crate::hyperfine::error::OptionsError;15 use crate::hyperfine::export::{ExportManager, ExportType};16 use crate::hyperfine::internal::write_benchmark_comparison;17+use crate::hyperfine::parameter_range::get_parameterized_commands;18 use crate::hyperfine::types::{19 BenchmarkResult, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption,20 };21 use crate::hyperfine::units::Unit;18 unmodified lines40 41 Ok(timing_results)42 }43 45-/// A function to read the `--parameter-scan` arguments46-fn 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()?;54-55- const MAX_PARAMETERS: i32 = 100_000;56- if param_max - param_min > MAX_PARAMETERS {57- return Err(ParameterScanError::TooLarge);58- }59-60- if param_max < param_min {61- return Err(ParameterScanError::EmptyRange);62- }63-64- if step_size == 0 {65- // Iterator::step_by panics for zero step66- return Err(ParameterScanError::ZeroStep);67- }68-69- let param_range = (param_min..(param_max + 1)).step_by(step_size);70-71- Ok((param_name, param_range))72-}73-44 fn 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 lines185 fn build_commands<'a>(matches: &'a ArgMatches<'_>) -> Vec<Command<'a>> {186 let command_strings = matches.values_of("command").unwrap();187 188 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 linesmodified:Cargo.lock+12 added
178 unmodified lines179 "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 lines517 version = "0.8.13"518 source = "registry+https://github.com/rust-lang/crates.io-index"519 520 [[package]]521+name = "rust_decimal"522+version = "1.0.3"523+source = "registry+https://github.com/rust-lang/crates.io-index"524+dependencies = [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+]529+530+[[package]]531 name = "rustc_version"532 version = "0.2.3"533 source = "registry+https://github.com/rust-lang/crates.io-index"534 dependencies = [232 unmodified lines767 "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 linesmodified:Cargo.toml+1 added
17 unmodified lines18192021222324252613 unmodified lines17 unmodified linescfg-if = "0.1.9"csv = "1.1.1"serde = { version = "1.0.99", features = ["derive"] }serde_json = "1.0.40"rust_decimal = "1.0"
[target.'cfg(not(windows))'.dependencies]libc = "0.2"
13 unmodified lines