executor.rs
This file
Path
src/benchmark/executor.rs
350 lines · 10.6 KiB · Rust
Last changed by
Initial work on tracking memory usageDavid Peterbefore adoption6556b2b
History of this fileTake it
1#[cfg(windows)]2use std::os::windows::process::CommandExt;3use std::process::ExitStatus;45use crate::command::Command;6use crate::options::{7 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,8};9use crate::output::progress_bar::get_progress_bar;10use crate::timer::{execute_and_measure, TimerResult};11use crate::util::randomized_environment_offset;12use crate::util::units::Second;1314use super::timing_result::TimingResult;1516use anyhow::{bail, Context, Result};17use statistical::mean;1819pub enum BenchmarkIteration {20 NonBenchmarkRun,21 Warmup(u64),22 Benchmark(u64),23}2425impl BenchmarkIteration {26 pub fn to_env_var_value(&self) -> Option<String> {27 match self {28 BenchmarkIteration::NonBenchmarkRun => None,29 BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)),30 BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)),31 }32 }33}3435pub trait Executor {36 /// Run the given command and measure the execution time37 fn run_command_and_measure(38 &self,39 command: &Command<'_>,40 iteration: BenchmarkIteration,41 command_failure_action: Option<CmdFailureAction>,42 output_policy: &CommandOutputPolicy,43 ) -> Result<(TimingResult, ExitStatus)>;4445 /// Perform a calibration of this executor. For example,46 /// when running commands through a shell, we need to47 /// measure the shell spawning time separately in order48 /// to subtract it from the full runtime later.49 fn calibrate(&mut self) -> Result<()>;5051 /// Return the time overhead for this executor when52 /// performing a measurement. This should return the time53 /// that is being used in addition to the actual runtime54 /// of the command.55 fn time_overhead(&self) -> Second;56}5758fn run_command_and_measure_common(59 mut command: std::process::Command,60 iteration: BenchmarkIteration,61 command_failure_action: CmdFailureAction,62 command_input_policy: &CommandInputPolicy,63 command_output_policy: &CommandOutputPolicy,64 command_name: &str,65) -> Result<TimerResult> {66 let stdin = command_input_policy.get_stdin()?;67 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;68 command.stdin(stdin).stdout(stdout).stderr(stderr);6970 command.env(71 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",72 randomized_environment_offset::value(),73 );7475 if let Some(value) = iteration.to_env_var_value() {76 command.env("HYPERFINE_ITERATION", value);77 }7879 let result = execute_and_measure(command)80 .with_context(|| format!("Failed to run command '{command_name}'"))?;8182 if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {83 let when = match iteration {84 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),85 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),86 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),87 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),88 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),89 };90 bail!(91 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \92 Alternatively, use the '--show-output' option to debug what went wrong.",93 cause=result.status.code().map_or(94 "The process has been terminated by a signal".into(),95 |c| format!("Command terminated with non-zero exit code {c}")9697 ),98 );99 }100101 Ok(result)102}103104pub struct RawExecutor<'a> {105 options: &'a Options,106}107108impl<'a> RawExecutor<'a> {109 pub fn new(options: &'a Options) -> Self {110 RawExecutor { options }111 }112}113114impl Executor for RawExecutor<'_> {115 fn run_command_and_measure(116 &self,117 command: &Command<'_>,118 iteration: BenchmarkIteration,119 command_failure_action: Option<CmdFailureAction>,120 output_policy: &CommandOutputPolicy,121 ) -> Result<(TimingResult, ExitStatus)> {122 let result = run_command_and_measure_common(123 command.get_command()?,124 iteration,125 command_failure_action.unwrap_or(self.options.command_failure_action),126 &self.options.command_input_policy,127 output_policy,128 &command.get_command_line(),129 )?;130131 Ok((132 TimingResult {133 time_real: result.time_real,134 time_user: result.time_user,135 time_system: result.time_system,136 memory_usage_byte: result.memory_usage_byte,137 },138 result.status,139 ))140 }141142 fn calibrate(&mut self) -> Result<()> {143 Ok(())144 }145146 fn time_overhead(&self) -> Second {147 0.0148 }149}150151pub struct ShellExecutor<'a> {152 options: &'a Options,153 shell: &'a Shell,154 shell_spawning_time: Option<TimingResult>,155}156157impl<'a> ShellExecutor<'a> {158 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {159 ShellExecutor {160 shell,161 options,162 shell_spawning_time: None,163 }164 }165}166167impl Executor for ShellExecutor<'_> {168 fn run_command_and_measure(169 &self,170 command: &Command<'_>,171 iteration: BenchmarkIteration,172 command_failure_action: Option<CmdFailureAction>,173 output_policy: &CommandOutputPolicy,174 ) -> Result<(TimingResult, ExitStatus)> {175 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");176 let mut command_builder = self.shell.command();177 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });178179 // Windows needs special treatment for its behavior on parsing cmd arguments180 if on_windows_cmd {181 #[cfg(windows)]182 command_builder.raw_arg(command.get_command_line());183 } else {184 command_builder.arg(command.get_command_line());185 }186187 let mut result = run_command_and_measure_common(188 command_builder,189 iteration,190 command_failure_action.unwrap_or(self.options.command_failure_action),191 &self.options.command_input_policy,192 output_policy,193 &command.get_command_line(),194 )?;195196 // Subtract shell spawning time197 if let Some(spawning_time) = self.shell_spawning_time {198 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);199 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);200 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);201 }202203 Ok((204 TimingResult {205 time_real: result.time_real,206 time_user: result.time_user,207 time_system: result.time_system,208 memory_usage_byte: result.memory_usage_byte,209 },210 result.status,211 ))212 }213214 /// Measure the average shell spawning time215 fn calibrate(&mut self) -> Result<()> {216 const COUNT: u64 = 50;217 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {218 Some(get_progress_bar(219 COUNT,220 "Measuring shell spawning time",221 self.options.output_style,222 ))223 } else {224 None225 };226227 let mut times_real: Vec<Second> = vec![];228 let mut times_user: Vec<Second> = vec![];229 let mut times_system: Vec<Second> = vec![];230231 for _ in 0..COUNT {232 // Just run the shell without any command233 let res = self.run_command_and_measure(234 &Command::new(None, ""),235 BenchmarkIteration::NonBenchmarkRun,236 None,237 &CommandOutputPolicy::Null,238 );239240 match res {241 Err(_) => {242 let shell_cmd = if cfg!(windows) {243 format!("{} /C \"\"", self.shell)244 } else {245 format!("{} -c \"\"", self.shell)246 };247248 bail!(249 "Could not measure shell execution time. Make sure you can run '{}'.",250 shell_cmd251 );252 }253 Ok((r, _)) => {254 times_real.push(r.time_real);255 times_user.push(r.time_user);256 times_system.push(r.time_system);257 }258 }259260 if let Some(bar) = progress_bar.as_ref() {261 bar.inc(1)262 }263 }264265 if let Some(bar) = progress_bar.as_ref() {266 bar.finish_and_clear()267 }268269 self.shell_spawning_time = Some(TimingResult {270 time_real: mean(×_real),271 time_user: mean(×_user),272 time_system: mean(×_system),273 memory_usage_byte: 0,274 });275276 Ok(())277 }278279 fn time_overhead(&self) -> Second {280 self.shell_spawning_time.unwrap().time_real281 }282}283284#[derive(Clone)]285pub struct MockExecutor {286 shell: Option<String>,287}288289impl MockExecutor {290 pub fn new(shell: Option<String>) -> Self {291 MockExecutor { shell }292 }293294 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {295 assert!(sleep_command.as_ref().starts_with("sleep "));296 sleep_command297 .as_ref()298 .trim_start_matches("sleep ")299 .parse::<Second>()300 .unwrap()301 }302}303304impl Executor for MockExecutor {305 fn run_command_and_measure(306 &self,307 command: &Command<'_>,308 _iteration: BenchmarkIteration,309 _command_failure_action: Option<CmdFailureAction>,310 _output_policy: &CommandOutputPolicy,311 ) -> Result<(TimingResult, ExitStatus)> {312 #[cfg(unix)]313 let status = {314 use std::os::unix::process::ExitStatusExt;315 ExitStatus::from_raw(0)316 };317318 #[cfg(windows)]319 let status = {320 use std::os::windows::process::ExitStatusExt;321 ExitStatus::from_raw(0)322 };323324 Ok((325 TimingResult {326 time_real: Self::extract_time(command.get_command_line()),327 time_user: 0.0,328 time_system: 0.0,329 memory_usage_byte: 0,330 },331 status,332 ))333 }334335 fn calibrate(&mut self) -> Result<()> {336 Ok(())337 }338339 fn time_overhead(&self) -> Second {340 match &self.shell {341 None => 0.0,342 Some(shell) => Self::extract_time(shell),343 }344 }345}346347#[test]348fn test_mock_executor_extract_time() {349 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);350}