Skip to content
Myr

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

6 files+376 added−181 removed

added:src/benchmark/executor.rs+230 added
1use std::process::{ExitStatus, Stdio};23use crate::command::Command;4use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};5use crate::output::progress_bar::get_progress_bar;6use crate::shell::execute_and_time;7use crate::timer::wallclocktimer::WallClockTimer;8use crate::timer::{TimerStart, TimerStop};9use crate::util::units::Second;1011use super::timing_result::TimingResult;1213use anyhow::{bail, Result};14use statistical::mean;1516pub trait Executor {17 fn time_command(18 &self,19 command: &Command<'_>,20 command_failure_action: Option<CmdFailureAction>,21 ) -> Result<(TimingResult, ExitStatus)>;2223 fn calibrate(&mut self) -> Result<()>;2425 fn time_overhead(&self) -> Second;26}2728pub struct ShellExecutor<'a> {29 options: &'a Options,30 shell: &'a Shell,31 shell_spawning_time: Option<TimingResult>,32}3334impl<'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 }4344 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {45 ShellExecutor {46 shell,47 options,48 shell_spawning_time: None,49 }50 }51}5253impl<'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 };6465 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();6869 let mut time_user = result.user_time;70 let mut time_system = result.system_time;7172 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 }8586 // 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 }9293 Ok((94 TimingResult {95 time_real,96 time_user,97 time_system,98 },99 result.status,100 ))101 }102103 /// 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 };115116 let mut times_real: Vec<Second> = vec![];117 let mut times_user: Vec<Second> = vec![];118 let mut times_system: Vec<Second> = vec![];119120 for _ in 0..COUNT {121 // Just run the shell without any command122 let res = self.time_command(&Command::new(None, ""), None);123124 match res {125 Err(_) => {126 let shell_cmd = if cfg!(windows) {127 format!("{} /C \"\"", self.shell)128 } else {129 format!("{} -c \"\"", self.shell)130 };131132 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 }143144 if let Some(bar) = progress_bar.as_ref() {145 bar.inc(1)146 }147 }148149 if let Some(bar) = progress_bar.as_ref() {150 bar.finish_and_clear()151 }152153 self.shell_spawning_time = Some(TimingResult {154 time_real: mean(&times_real),155 time_user: mean(&times_user),156 time_system: mean(&times_system),157 });158159 Ok(())160 }161162 fn time_overhead(&self) -> Second {163 self.shell_spawning_time.unwrap().time_real164 }165}166167#[derive(Clone)]168pub struct MockExecutor<'a> {169 shell: &'a Shell,170}171172impl<'a> MockExecutor<'a> {173 pub fn new(shell: &'a Shell) -> Self {174 MockExecutor { shell }175 }176177 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}186187impl<'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 };198199 #[cfg(windows)]200 let status = {201 use std::os::windows::process::ExitStatusExt;202 ExitStatus::from_raw(0)203 };204205 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 }214215 fn calibrate(&mut self) -> Result<()> {216 Ok(())217 }218219 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}226227#[test]228fn 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
1pub mod benchmark_result;2pub mod executor;3pub mod relative_speed;4pub mod scheduler;5pub mod timing_result;67use std::cmp;7use std::process::{ExitStatus, Stdio};89use crate::command::Command;10use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};10use crate::options::{CmdFailureAction, Options, OutputStyleOption};11use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};12use crate::output::format::{format_duration, format_duration_unit};13use crate::output::progress_bar::get_progress_bar;14use crate::output::warnings::Warnings;15use crate::parameter::ParameterNameAndValue;16use crate::shell::execute_and_time;17use crate::timer::wallclocktimer::WallClockTimer;18use crate::timer::{TimerStart, TimerStop};16use crate::util::exit_code::extract_exit_code;17use crate::util::min_max::{max, min};18use crate::util::units::Second;19use benchmark_result::BenchmarkResult;20use timing_result::TimingResult;2125use anyhow::{anyhow, bail, Result};22use anyhow::{anyhow, Result};23use colored::*;24use statistical::{mean, median, standard_deviation};2526use self::executor::Executor;2728/// Threshold for warning about fast execution time29pub const MIN_EXECUTION_TIME: Second = 5e-3;3032/////////////// TODO: refactor the following part3334/// Correct for shell spawning time35fn 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}4243/// Run the given shell command and measure the execution time44pub 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 };5556 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();5960 let mut time_user = result.user_time;61 let mut time_system = result.system_time;6263 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 }7374 // 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 }8081 Ok((82 TimingResult {83 time_real,84 time_user,85 time_system,86 },87 result.status,88 ))89}9091/// Measure the average shell spawning time92pub 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 };107108 let mut times_real: Vec<Second> = vec![];109 let mut times_user: Vec<Second> = vec![];110 let mut times_system: Vec<Second> = vec![];111112 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 );121122 match res {123 Err(_) => {124 let shell_cmd = if cfg!(windows) {125 format!("{} /C \"\"", shell)126 } else {127 format!("{} -c \"\"", shell)128 };129130 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 }141142 if let Some(bar) = progress_bar.as_ref() {143 bar.inc(1)144 }145 }146147 if let Some(bar) = progress_bar.as_ref() {148 bar.finish_and_clear()149 }150151 Ok(TimingResult {152 time_real: mean(&times_real),153 time_user: mean(&times_user),154 time_system: mean(&times_system),155 })156}157///////////////15831pub 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}3738impl<'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 }5253 /// Run setup, cleanup, or preparation commands
1 unmodified line
55 &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 }6465 /// Run the command specified by `--setup`.66 fn run_setup_command(
96 unmodified lines
163 };164165 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 lines
187188 let preparation_result = run_preparation_command()?;189190 // 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();193194 // 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;198199 let count = {200 let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);
36 unmodified lines
237 if let Some(bar) = progress_bar.as_ref() {238 bar.set_message(msg.to_owned())239 }240386 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();243244 times_real.push(res.time_real);245 times_user.push(res.time_user);
127 unmodified lines
modified:src/benchmark/scheduler.rs+9 added-8 removed
1use colored::*;23use super::benchmark_result::BenchmarkResult;4use super::executor::{Executor, MockExecutor, ShellExecutor};5use super::{relative_speed, Benchmark};67use crate::command::Commands;8use crate::export::ExportManager;8use crate::options::{Options, OutputStyleOption};9use crate::options::{ExecutorKind, Options, OutputStyleOption};1011use anyhow::Result;1213pub struct Scheduler<'a> {
17 unmodified lines
31 }32 }3334 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 };3940 executor.calibrate()?;4142 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()?);4546 // 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_manager
48 unmodified lines
modified:src/app.rs+6 added
247 unmodified lines
248 .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}259260#[test]261fn verify_app() {
2 unmodified lines
modified:src/options.rs+21 added-6 removed
122 unmodified lines
123 CommandOutputPolicy::Discard124 }125}126127pub enum ExecutorKind {128 Shell(Shell),129 Mock(Shell),130}131132impl Default for ExecutorKind {133 fn default() -> Self {134 ExecutorKind::Shell(Shell::default())135 }136}137138/// The main settings for a hyperfine benchmark session139pub struct Options {140 /// Upper and lower bound for the number of benchmark runs141 pub run_bounds: RunBounds,
18 unmodified lines
160161 /// What color mode to use for the terminal output162 pub output_style: OutputStyleOption,163153 /// The shell to use for executing commands.154 pub shell: Shell,164 /// Determines how we run commands165 pub executor_kind: ExecutorKind,166167 /// What to do with the output of the benchmarked command168 pub command_output_policy: CommandOutputPolicy,169
11 unmodified lines
181 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 lines
271 }272 OutputStyleOption::Disabled => {}273 };274264 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 };282283 if matches.is_present("ignore-failure") {284 options.command_failure_action = CmdFailureAction::Ignore;285 }
67 unmodified lines
modified:tests/integration_tests.rs+94 added
1 unmodified line
2use common::hyperfine;34use predicates::prelude::*;56pub fn hyperfine_debug() -> assert_cmd::Command {7 let mut cmd = hyperfine();8 cmd.arg("--debug-mode");9 cmd10}1112#[test]13fn hyperfine_runs_successfully() {14 hyperfine()15 .arg("--runs=2")
146 unmodified lines
162 predicate::str::contains("custom_shell --shell-arg /C echo benchmark"),163 ),164 );165}166167#[test]168fn 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 ±"));174175 hyperfine_debug()176 .arg("sleep 0.123")177 .assert()178 .success()179 .stdout(predicate::str::contains("Time (mean ± σ): 123.0 ms ±"));180181 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}188189#[test]190fn 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}198199#[test]200fn 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}208209#[test]210fn 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}219220#[test]221fn 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}233234#[test]235fn 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}