Add debug/mock mode
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Peter · committed by David Peter · parent 3348b37 · Browse files · 6 files·+376 added−181 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+376 added−181 removed
- tests:+94 added−0 removed
- other:+282 added−181 removed
Provenance
- Commit
6f51232- Tree
ee0d907- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
3348b37
6 files changed+376 added−181 removed
added:src/benchmark/executor.rs+230 added
1+use std::process::{ExitStatus, Stdio};2+3+use crate::command::Command;4+use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};5+use crate::output::progress_bar::get_progress_bar;6+use crate::shell::execute_and_time;7+use crate::timer::wallclocktimer::WallClockTimer;8+use crate::timer::{TimerStart, TimerStop};9+use crate::util::units::Second;10+11+use super::timing_result::TimingResult;12+13+use anyhow::{bail, Result};14+use statistical::mean;15+16+pub trait Executor {17+ fn time_command(18+ &self,19+ command: &Command<'_>,20+ command_failure_action: Option<CmdFailureAction>,21+ ) -> Result<(TimingResult, ExitStatus)>;22+23+ fn calibrate(&mut self) -> Result<()>;24+25+ fn time_overhead(&self) -> Second;26+}27+28+pub struct ShellExecutor<'a> {29+ options: &'a Options,30+ shell: &'a Shell,31+ shell_spawning_time: Option<TimingResult>,32+}33+34+impl<'a> ShellExecutor<'a> {35+ /// Correct for shell spawning time36+ fn subtract_shell_spawning_time(&self, time: Second, shell_spawning_time: Second) -> Second {37+ if time < shell_spawning_time {38+ 0.039+ } else {40+ time - shell_spawning_time41+ }42+ }43+44+ pub fn new(shell: &'a Shell, options: &'a Options) -> Self {45+ ShellExecutor {46+ shell,47+ options,48+ shell_spawning_time: None,49+ }50+ }51+}52+53+impl<'a> Executor for ShellExecutor<'a> {54+ /// Run the given shell command and measure the execution time55+ fn time_command(56+ &self,57+ command: &Command<'_>,58+ command_failure_action: Option<CmdFailureAction>,59+ ) -> Result<(TimingResult, ExitStatus)> {60+ let (stdout, stderr) = match self.options.command_output_policy {61+ CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),62+ CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),63+ };64+65+ let wallclock_timer = WallClockTimer::start();66+ let result = execute_and_time(stdout, stderr, &command.get_shell_command(), &self.shell)?;67+ let mut time_real = wallclock_timer.stop();68+69+ let mut time_user = result.user_time;70+ let mut time_system = result.system_time;71+72+ if command_failure_action.unwrap_or(self.options.command_failure_action)73+ == CmdFailureAction::RaiseError74+ && !result.status.success()75+ {76+ bail!(77+ "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \78+ Alternatively, use the '--show-output' option to debug what went wrong.",79+ result.status.code().map_or(80+ "The process has been terminated by a signal".into(),81+ |c| format!("Command terminated with non-zero exit code: {}", c)82+ )83+ );84+ }85+86+ // Subtract shell spawning time87+ if let Some(spawning_time) = self.shell_spawning_time {88+ time_real = self.subtract_shell_spawning_time(time_real, spawning_time.time_real);89+ time_user = self.subtract_shell_spawning_time(time_user, spawning_time.time_user);90+ time_system = self.subtract_shell_spawning_time(time_system, spawning_time.time_system);91+ }92+93+ Ok((94+ TimingResult {95+ time_real,96+ time_user,97+ time_system,98+ },99+ result.status,100+ ))101+ }102+103+ /// Measure the average shell spawning time104+ fn calibrate(&mut self) -> Result<()> {105+ const COUNT: u64 = 50;106+ let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {107+ Some(get_progress_bar(108+ COUNT,109+ "Measuring shell spawning time",110+ self.options.output_style,111+ ))112+ } else {113+ None114+ };115+116+ let mut times_real: Vec<Second> = vec![];117+ let mut times_user: Vec<Second> = vec![];118+ let mut times_system: Vec<Second> = vec![];119+120+ for _ in 0..COUNT {121+ // Just run the shell without any command122+ let res = self.time_command(&Command::new(None, ""), None);123+124+ match res {125+ Err(_) => {126+ let shell_cmd = if cfg!(windows) {127+ format!("{} /C \"\"", self.shell)128+ } else {129+ format!("{} -c \"\"", self.shell)130+ };131+132+ bail!(133+ "Could not measure shell execution time. Make sure you can run '{}'.",134+ shell_cmd135+ );136+ }137+ Ok((r, _)) => {138+ times_real.push(r.time_real);139+ times_user.push(r.time_user);140+ times_system.push(r.time_system);141+ }142+ }143+144+ if let Some(bar) = progress_bar.as_ref() {145+ bar.inc(1)146+ }147+ }148+149+ if let Some(bar) = progress_bar.as_ref() {150+ bar.finish_and_clear()151+ }152+153+ self.shell_spawning_time = Some(TimingResult {154+ time_real: mean(×_real),155+ time_user: mean(×_user),156+ time_system: mean(×_system),157+ });158+159+ Ok(())160+ }161+162+ fn time_overhead(&self) -> Second {163+ self.shell_spawning_time.unwrap().time_real164+ }165+}166+167+#[derive(Clone)]168+pub struct MockExecutor<'a> {169+ shell: &'a Shell,170+}171+172+impl<'a> MockExecutor<'a> {173+ pub fn new(shell: &'a Shell) -> Self {174+ MockExecutor { shell }175+ }176+177+ fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {178+ assert!(sleep_command.as_ref().starts_with("sleep "));179+ sleep_command180+ .as_ref()181+ .trim_start_matches("sleep ")182+ .parse::<Second>()183+ .unwrap()184+ }185+}186+187+impl<'a> Executor for MockExecutor<'a> {188+ fn time_command(189+ &self,190+ command: &Command<'_>,191+ _command_failure_action: Option<CmdFailureAction>,192+ ) -> Result<(TimingResult, ExitStatus)> {193+ #[cfg(unix)]194+ let status = {195+ use std::os::unix::process::ExitStatusExt;196+ ExitStatus::from_raw(0)197+ };198+199+ #[cfg(windows)]200+ let status = {201+ use std::os::windows::process::ExitStatusExt;202+ ExitStatus::from_raw(0)203+ };204+205+ Ok((206+ TimingResult {207+ time_real: Self::extract_time(command.get_shell_command()),208+ time_user: 0.0,209+ time_system: 0.0,210+ },211+ status,212+ ))213+ }214+215+ fn calibrate(&mut self) -> Result<()> {216+ Ok(())217+ }218+219+ fn time_overhead(&self) -> Second {220+ match self.shell {221+ Shell::Default(_) => 0.0,222+ Shell::Custom(shell) => Self::extract_time(&shell[0]),223+ }224+ }225+}226+227+#[test]228+fn test_mock_executor_extract_time() {229+ assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);230+}modified:src/benchmark/mod.rs+16 added-167 removed
1 pub mod benchmark_result;2+pub mod executor;3 pub mod relative_speed;4 pub mod scheduler;5 pub mod timing_result;6 7 use std::cmp;7-use std::process::{ExitStatus, Stdio};8 9 use crate::command::Command;10-use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};10+use crate::options::{CmdFailureAction, Options, OutputStyleOption};11 use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};12 use crate::output::format::{format_duration, format_duration_unit};13 use crate::output::progress_bar::get_progress_bar;14 use crate::output::warnings::Warnings;15 use crate::parameter::ParameterNameAndValue;16-use crate::shell::execute_and_time;17-use crate::timer::wallclocktimer::WallClockTimer;18-use crate::timer::{TimerStart, TimerStop};16 use crate::util::exit_code::extract_exit_code;17 use crate::util::min_max::{max, min};18 use crate::util::units::Second;19 use benchmark_result::BenchmarkResult;20 use timing_result::TimingResult;21 25-use anyhow::{anyhow, bail, Result};22+use anyhow::{anyhow, Result};23 use colored::*;24 use statistical::{mean, median, standard_deviation};25 26+use self::executor::Executor;27+28 /// Threshold for warning about fast execution time29 pub const MIN_EXECUTION_TIME: Second = 5e-3;30 32-/////////////// TODO: refactor the following part33-34-/// Correct for shell spawning time35-fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {36- if time < shell_spawning_time {37- 0.038- } else {39- time - shell_spawning_time40- }41-}42-43-/// Run the given shell command and measure the execution time44-pub fn time_shell_command(45- shell: &Shell,46- command: &Command<'_>,47- command_output_policy: CommandOutputPolicy,48- failure_action: CmdFailureAction,49- shell_spawning_time: Option<&TimingResult>,50-) -> Result<(TimingResult, ExitStatus)> {51- let (stdout, stderr) = match command_output_policy {52- CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),53- CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),54- };55-56- let wallclock_timer = WallClockTimer::start();57- let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;58- let mut time_real = wallclock_timer.stop();59-60- let mut time_user = result.user_time;61- let mut time_system = result.system_time;62-63- if failure_action == CmdFailureAction::RaiseError && !result.status.success() {64- bail!(65- "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \66- Alternatively, use the '--show-output' option to debug what went wrong.",67- result.status.code().map_or(68- "The process has been terminated by a signal".into(),69- |c| format!("Command terminated with non-zero exit code: {}", c)70- )71- );72- }73-74- // Correct for shell spawning time75- if let Some(spawning_time) = shell_spawning_time {76- time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);77- time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);78- time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);79- }80-81- Ok((82- TimingResult {83- time_real,84- time_user,85- time_system,86- },87- result.status,88- ))89-}90-91-/// Measure the average shell spawning time92-pub fn mean_shell_spawning_time(93- shell: &Shell,94- style: OutputStyleOption,95- command_output_policy: CommandOutputPolicy,96-) -> Result<TimingResult> {97- const COUNT: u64 = 50;98- let progress_bar = if style != OutputStyleOption::Disabled {99- Some(get_progress_bar(100- COUNT,101- "Measuring shell spawning time",102- style,103- ))104- } else {105- None106- };107-108- let mut times_real: Vec<Second> = vec![];109- let mut times_user: Vec<Second> = vec![];110- let mut times_system: Vec<Second> = vec![];111-112- for _ in 0..COUNT {113- // Just run the shell without any command114- let res = time_shell_command(115- shell,116- &Command::new(None, ""),117- command_output_policy,118- CmdFailureAction::RaiseError,119- None,120- );121-122- match res {123- Err(_) => {124- let shell_cmd = if cfg!(windows) {125- format!("{} /C \"\"", shell)126- } else {127- format!("{} -c \"\"", shell)128- };129-130- bail!(131- "Could not measure shell execution time. Make sure you can run '{}'.",132- shell_cmd133- );134- }135- Ok((r, _)) => {136- times_real.push(r.time_real);137- times_user.push(r.time_user);138- times_system.push(r.time_system);139- }140- }141-142- if let Some(bar) = progress_bar.as_ref() {143- bar.inc(1)144- }145- }146-147- if let Some(bar) = progress_bar.as_ref() {148- bar.finish_and_clear()149- }150-151- Ok(TimingResult {152- time_real: mean(×_real),153- time_user: mean(×_user),154- time_system: mean(×_system),155- })156-}157-///////////////158-31 pub struct Benchmark<'a> {32 number: usize,33 command: &'a Command<'a>,34 options: &'a Options,163- shell_spawning_time: &'a TimingResult,35+ executor: &'a dyn Executor,36 }37 38 impl<'a> Benchmark<'a> {39 pub fn new(40 number: usize,41 command: &'a Command<'a>,42 options: &'a Options,171- shell_spawning_time: &'a TimingResult,43+ executor: &'a dyn Executor,44 ) -> Self {45 Benchmark {46 number,47 command,48 options,177- shell_spawning_time,49+ executor,50 }51 }52 53 /// Run setup, cleanup, or preparation commands1 unmodified line55 &self,56 command: &Command<'_>,57 error_output: &'static str,58 ) -> Result<TimingResult> {187- time_shell_command(188- &self.options.shell,189- command,190- self.options.command_output_policy,191- CmdFailureAction::RaiseError,192- None,193- )194- .map(|r| r.0)195- .map_err(|_| anyhow!(error_output))59+ self.executor60+ .time_command(command, Some(CmdFailureAction::RaiseError))61+ .map(|r| r.0)62+ .map_err(|_| anyhow!(error_output))63 }64 65 /// Run the command specified by `--setup`.66 fn run_setup_command(96 unmodified lines163 };164 165 for _ in 0..self.options.warmup_count {166 let _ = run_preparation_command()?;300- let _ = time_shell_command(301- &self.options.shell,302- self.command,303- self.options.command_output_policy,304- self.options.command_failure_action,305- None,306- )?;167+ let _ = self.executor.time_command(self.command, None)?;168 if let Some(bar) = progress_bar.as_ref() {169 bar.inc(1)170 }171 }15 unmodified lines187 188 let preparation_result = run_preparation_command()?;189 190 // Initial timing run330- let (res, status) = time_shell_command(331- &self.options.shell,332- self.command,333- self.options.command_output_policy,334- self.options.command_failure_action,335- Some(&self.shell_spawning_time),336- )?;191+ let (res, status) = self.executor.time_command(self.command, None)?;192 let success = status.success();193 194 // Determine number of benchmark runs195 let runs_in_min_time = (self.options.min_benchmarking_time341- / (res.time_real + preparation_result.time_real + self.shell_spawning_time.time_real))196+ / (res.time_real + preparation_result.time_real + self.executor.time_overhead()))197 as u64;198 199 let count = {200 let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);36 unmodified lines237 if let Some(bar) = progress_bar.as_ref() {238 bar.set_message(msg.to_owned())239 }240 386- let (res, status) = time_shell_command(387- &self.options.shell,388- self.command,389- self.options.command_output_policy,390- self.options.command_failure_action,391- Some(self.shell_spawning_time),392- )?;241+ let (res, status) = self.executor.time_command(self.command, None)?;242 let success = status.success();243 244 times_real.push(res.time_real);245 times_user.push(res.time_user);127 unmodified linesmodified:src/benchmark/scheduler.rs+9 added-8 removed
1 use colored::*;2 3 use super::benchmark_result::BenchmarkResult;4+use super::executor::{Executor, MockExecutor, ShellExecutor};5 use super::{relative_speed, Benchmark};6 7 use crate::command::Commands;8 use crate::export::ExportManager;8-use crate::options::{Options, OutputStyleOption};9+use crate::options::{ExecutorKind, Options, OutputStyleOption};10 11 use anyhow::Result;12 13 pub struct Scheduler<'a> {17 unmodified lines31 }32 }33 34 pub fn run_benchmarks(&mut self) -> Result<()> {34- let shell_spawning_time = super::mean_shell_spawning_time(35- // TODO36- &self.options.shell,37- self.options.output_style,38- self.options.command_output_policy,39- )?;35+ let mut executor: Box<dyn Executor> = match self.options.executor_kind {36+ ExecutorKind::Mock(ref shell) => Box::new(MockExecutor::new(shell)),37+ ExecutorKind::Shell(ref shell) => Box::new(ShellExecutor::new(shell, &self.options)),38+ };39 40+ executor.calibrate()?;41+42 for (number, cmd) in self.commands.iter().enumerate() {43 self.results43- .push(Benchmark::new(number, cmd, self.options, &shell_spawning_time).run()?);44+ .push(Benchmark::new(number, cmd, self.options, &*executor).run()?);45 46 // We export (all results so far) after each individual benchmark, because47 // we would risk losing all results if a later benchmark fails.48 self.export_manager48 unmodified linesmodified:src/app.rs+6 added
247 unmodified lines248 .value_name("NAME")249 .help("Give a meaningful name to a command. This can be specified multiple times \250 if several commands are benchmarked."),251 )252+ .arg(253+ Arg::new("debug-mode")254+ .long("debug-mode")255+ .hide(true)256+ .help("Enable debug mode which does not actually run commands, but returns fake times when the command is 'sleep <time>'")257+ )258 }259 260 #[test]261 fn verify_app() {2 unmodified linesmodified:src/options.rs+21 added-6 removed
122 unmodified lines123 CommandOutputPolicy::Discard124 }125 }126 127+pub enum ExecutorKind {128+ Shell(Shell),129+ Mock(Shell),130+}131+132+impl Default for ExecutorKind {133+ fn default() -> Self {134+ ExecutorKind::Shell(Shell::default())135+ }136+}137+138 /// The main settings for a hyperfine benchmark session139 pub struct Options {140 /// Upper and lower bound for the number of benchmark runs141 pub run_bounds: RunBounds,18 unmodified lines160 161 /// What color mode to use for the terminal output162 pub output_style: OutputStyleOption,163 153- /// The shell to use for executing commands.154- pub shell: Shell,164+ /// Determines how we run commands165+ pub executor_kind: ExecutorKind,166 167 /// What to do with the output of the benchmarked command168 pub command_output_policy: CommandOutputPolicy,169 11 unmodified lines181 preparation_command: None,182 setup_command: None,183 cleanup_command: None,184 output_style: OutputStyleOption::Full,174- shell: Shell::default(),185+ executor_kind: ExecutorKind::default(),186 command_output_policy: CommandOutputPolicy::Discard,187 time_unit: None,188 }189 }81 unmodified lines271 }272 OutputStyleOption::Disabled => {}273 };274 264- if let Some(shell) = matches.value_of("shell") {265- options.shell = Shell::from_str(shell)?;266- }275+ options.executor_kind = match (matches.is_present("debug-mode"), matches.value_of("shell"))276+ {277+ (false, Some(shell)) => ExecutorKind::Shell(Shell::from_str(shell)?),278+ (false, None) => ExecutorKind::Shell(Shell::default()),279+ (true, Some(shell)) => ExecutorKind::Mock(Shell::from_str(shell)?),280+ (true, None) => ExecutorKind::Mock(Shell::default()),281+ };282 283 if matches.is_present("ignore-failure") {284 options.command_failure_action = CmdFailureAction::Ignore;285 }67 unmodified linesmodified:tests/integration_tests.rs+94 added
1 unmodified line2 use common::hyperfine;3 4 use predicates::prelude::*;5 6+pub fn hyperfine_debug() -> assert_cmd::Command {7+ let mut cmd = hyperfine();8+ cmd.arg("--debug-mode");9+ cmd10+}11+12 #[test]13 fn hyperfine_runs_successfully() {14 hyperfine()15 .arg("--runs=2")146 unmodified lines162 predicate::str::contains("custom_shell --shell-arg /C echo benchmark"),163 ),164 );165 }166+167+#[test]168+fn returns_mean_time_in_correct_unit() {169+ hyperfine_debug()170+ .arg("sleep 1.234")171+ .assert()172+ .success()173+ .stdout(predicate::str::contains("Time (mean ± σ): 1.234 s ±"));174+175+ hyperfine_debug()176+ .arg("sleep 0.123")177+ .assert()178+ .success()179+ .stdout(predicate::str::contains("Time (mean ± σ): 123.0 ms ±"));180+181+ hyperfine_debug()182+ .arg("--time-unit=millisecond")183+ .arg("sleep 1.234")184+ .assert()185+ .success()186+ .stdout(predicate::str::contains("Time (mean ± σ): 1234.0 ms ±"));187+}188+189+#[test]190+fn performs_ten_runs_for_slow_commands() {191+ hyperfine_debug()192+ .arg("--time-unit=millisecond")193+ .arg("sleep 0.5")194+ .assert()195+ .success()196+ .stdout(predicate::str::contains("10 runs"));197+}198+199+#[test]200+fn performs_three_seconds_of_benchmarking_for_fast_commands() {201+ hyperfine_debug()202+ .arg("--time-unit=millisecond")203+ .arg("sleep 0.01")204+ .assert()205+ .success()206+ .stdout(predicate::str::contains("300 runs"));207+}208+209+#[test]210+fn takes_time_of_preparation_command_into_account() {211+ hyperfine_debug()212+ .arg("--time-unit=millisecond")213+ .arg("--prepare=sleep 0.02")214+ .arg("sleep 0.01")215+ .assert()216+ .success()217+ .stdout(predicate::str::contains("100 runs"));218+}219+220+#[test]221+fn shows_benchmark_comparison_with_relative_times() {222+ hyperfine_debug()223+ .arg("sleep 1.0")224+ .arg("sleep 2.0")225+ .arg("sleep 3.0")226+ .assert()227+ .success()228+ .stdout(229+ predicate::str::contains("2.00 ± 0.00 times faster")230+ .and(predicate::str::contains("3.00 ± 0.00 times faster")),231+ );232+}233+234+#[test]235+fn performs_all_benchmarks_in_parameter_scan() {236+ hyperfine_debug()237+ .arg("--parameter-scan")238+ .arg("time")239+ .arg("30")240+ .arg("45")241+ .arg("--parameter-step-size")242+ .arg("5")243+ .arg("sleep {time}")244+ .assert()245+ .success()246+ .stdout(247+ predicate::str::contains("Benchmark 1: sleep 30")248+ .and(predicate::str::contains("Benchmark 2: sleep 35"))249+ .and(predicate::str::contains("Benchmark 3: sleep 40"))250+ .and(predicate::str::contains("Benchmark 4: sleep 45"))251+ .and(predicate::str::contains("Benchmark 5: sleep 50").not()),252+ );253+}