Skip to content
Myr

Run setup/cleanup commands in a shell (#990)

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

authored by David Peter · committed by GitHub · parent e4a3213 · Browse files · 6 files+103 added−80 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+103 added−80 removed

  • tests:+19 added−19 removed
  • other:+84 added−61 removed

6 files+103 added−80 removed

modified:doc/hyperfine.1+6 added-4 removed
192 unmodified lines
193possible parameter combinations.194.HP195\fB\-\-shell\fR \fISHELL\fP196.IP197Set the shell to use for executing commands (default: none). This can be198the name or the path to the shell executable, or a full command line197Set the shell to use for executing benchmarked commands, including warmup runs198(default: none). This can be the name or the path to the shell executable,199or a full command line200like "bash \fB\-\-norc\fR". It can also be set to "default" to explicitly201select the platform shell (sh on Unix, cmd.exe on Windows). Finally, this can also be201set to "none" to disable the shell. In this case, commands will be202set to "none" to disable the shell. In this case, benchmarked commands will be203executed directly. They can still have arguments, but more complex204things like "sleep 0.1; sleep 0.2" are not possible without a shell.204This option also applies to setup, prepare, conclude, and cleanup commands.205Setup, prepare, conclude, and cleanup commands always use a shell: the selected206shell, or the platform shell when this option is omitted or set to "none".207.HP208\fB\-S\fR209.IP210An alias for '\-\-shell=default' (sh on Unix, cmd.exe on Windows).
182 unmodified lines
modified:src/benchmark/executor.rs+51 added-20 removed
3 unmodified lines
45use crate::benchmark::measurement::Measurement;6use crate::benchmark::measurement::Measurements;7use crate::command::Command;8use crate::options::{9 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,10};8use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};9use crate::output::progress_bar::get_progress_bar;10use crate::quantity::{second, Information, Time, Zero};11use crate::timer::execute_and_measure;12use crate::util::randomized_environment_offset;
26 unmodified lines
39 command_failure_action: Option<CmdFailureAction>,40 output_policy: &CommandOutputPolicy,41 ) -> Result<Measurement>;4243 /// Run a lifecycle command through a shell, always treating failures as errors.44 fn run_intermediate_command_and_measure(45 &self,46 command: &Command<'_>,47 iteration: BenchmarkIteration,48 output_policy: &CommandOutputPolicy,49 ) -> Result<Measurement> {50 self.run_command_and_measure(51 command,52 iteration,53 Some(CmdFailureAction::RaiseError),54 output_policy,55 )56 }5758 /// Perform a calibration of this executor. For example,59 /// when running commands through a shell, we need to60 /// measure the shell spawning time separately in order61 /// to subtract it from the full runtime later.
8 unmodified lines
7071fn run_command_and_measure_common(72 mut command: std::process::Command,73 iteration: BenchmarkIteration,61 command_failure_action: CmdFailureAction,62 command_input_policy: &CommandInputPolicy,74 command_failure_action: Option<CmdFailureAction>,75 options: &Options,76 command_output_policy: &CommandOutputPolicy,77 command_name: &str,78 collect_hardware_counters: bool,79) -> Result<Measurement> {67 let stdin = command_input_policy.get_stdin()?;80 let stdin = options.command_input_policy.get_stdin()?;81 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;82 command.stdin(stdin).stdout(stdout).stderr(stderr);8384 command.env(
10 unmodified lines
9596 if !measurement.exit_status.success() {97 use crate::util::exit_code::extract_exit_code;9899 let show_ignore_failure_hint = command_failure_action.is_none();86 let should_fail = match command_failure_action {100 let should_fail = match command_failure_action101 .as_ref()102 .unwrap_or(&options.command_failure_action)103 {104 CmdFailureAction::RaiseError => true,105 CmdFailureAction::IgnoreAllFailures => false,89 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {106 CmdFailureAction::IgnoreSpecificFailures(codes) => {107 // Only fail if the exit code is not in the list of codes to ignore108 if let Some(exit_code) = extract_exit_code(measurement.exit_status) {109 !codes.contains(&exit_code)110 } else {
10 unmodified lines
121 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),122 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),123 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),124 };108 bail!(109 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \110 Alternatively, use the '--show-output' option to debug what went wrong.",111 cause=measurement.exit_status.code().map_or(112 "The process has been terminated by a signal".into(),113 |c| format!("Command terminated with non-zero exit code {c}")114115 ),125 let cause = measurement.exit_status.code().map_or_else(126 || "was terminated by a signal".to_owned(),127 |code| format!("terminated with non-zero exit code {code}"),128 );129 let hint = if show_ignore_failure_hint {130 " Use the '-i'/'--ignore-failure' option if you want to ignore this. \131 Alternatively, use the '--show-output' option to debug what went wrong."132 } else {133 " Use the '--show-output' option to debug what went wrong."134 };135 bail!("Command '{command_name}' {cause} in {when}.{hint}");136 }137 }138139 Ok(measurement)
19 unmodified lines
159 ) -> Result<Measurement> {160 run_command_and_measure_common(161 command.get_command()?,162 iteration,144 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),145 &self.options.command_input_policy,163 command_failure_action,164 self.options,165 output_policy,166 &command.get_command_line(),167 matches!(iteration, BenchmarkIteration::Benchmark(_)),168 )169 }170171 fn run_intermediate_command_and_measure(172 &self,173 command: &Command<'_>,174 iteration: BenchmarkIteration,175 output_policy: &CommandOutputPolicy,176 ) -> Result<Measurement> {177 // Keep shell startup in the hook's duration: raw benchmarks have no178 // calibrated shell overhead to add back when estimating the run count.179 ShellExecutor::new(&Shell::platform_default(), self.options)180 .run_intermediate_command_and_measure(command, iteration, output_policy)181 }182183 fn calibrate(&mut self) -> Result<()> {184 Ok(())185 }186
40 unmodified lines
227228 let mut measurement = run_command_and_measure_common(229 command_builder,230 iteration,200 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),201 &self.options.command_input_policy,231 command_failure_action,232 self.options,233 output_policy,234 &command.get_command_line(),235 false,236 )?;
164 unmodified lines
modified:src/benchmark/mod.rs+16 added-28 removed
9 unmodified lines
10use crate::benchmark::benchmark_result::Parameter;11use crate::benchmark::executor::BenchmarkIteration;12use crate::benchmark::measurement::{Measurement, Measurements};13use crate::command::Command;14use crate::options::{15 CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,16};14use crate::options::{CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption};15use crate::outlier_detection::OUTLIER_THRESHOLD;16use crate::output::console_writeln;17use crate::output::progress_bar::{18 finish_initial_measurement, get_progress_bar, set_benchmark_header, start_initial_measurement,
33 unmodified lines
52 executor,53 }54 }5558 /// Run setup, cleanup, or preparation commands56 /// Run setup, cleanup, preparation, or conclusion commands57 fn run_intermediate_command(58 &self,59 command: &Command<'_>,62 error_output: &'static str,60 kind: &'static str,61 output_policy: &CommandOutputPolicy,62 iteration: executor::BenchmarkIteration,63 ) -> Result<Measurement> {64 self.executor67 .run_command_and_measure(68 command,69 iteration,70 Some(CmdFailureAction::RaiseError),71 output_policy,72 )73 .map_err(|_| anyhow!(error_output))65 .run_intermediate_command_and_measure(command, iteration, output_policy)66 .map_err(|error| {67 let hint = if cfg!(windows) {68 "Append ' || exit /b 0' to the command if this failure can be ignored."69 } else {70 "Append ' || true' to the command if this failure can be ignored."71 };72 anyhow!("The {kind} command failed: {error:#} {hint}")73 })74 }7576 /// Run the command specified by `--setup`.77 fn run_setup_command(
6 unmodified lines
84 .setup_command85 .as_ref()86 .map(|setup_command| Command::new_parametrized(None, setup_command, parameters));8788 let error_output = "The setup command terminated with a non-zero exit code. \89 Append ' || true' to the command if you are sure that this can be ignored.";9088 Ok(command89 .map(|cmd| {90 self.run_intermediate_command(91 &cmd,95 error_output,92 "setup",93 output_policy,94 BenchmarkIteration::NonBenchmarkRun,95 )96 })
12 unmodified lines
109 .cleanup_command110 .as_ref()111 .map(|cleanup_command| Command::new_parametrized(None, cleanup_command, parameters));112116 let error_output = "The cleanup command terminated with a non-zero exit code. \117 Append ' || true' to the command if you are sure that this can be ignored.";118113 Ok(command114 .map(|cmd| {115 self.run_intermediate_command(116 &cmd,123 error_output,117 "cleanup",118 output_policy,119 BenchmarkIteration::NonBenchmarkRun,120 )121 })
7 unmodified lines
129 command: &Command<'_>,130 output_policy: &CommandOutputPolicy,131 iteration: executor::BenchmarkIteration,132 ) -> Result<Measurement> {139 let error_output = "The preparation command terminated with a non-zero exit code. \140 Append ' || true' to the command if you are sure that this can be ignored.";141142 self.run_intermediate_command(command, error_output, output_policy, iteration)133 self.run_intermediate_command(command, "preparation", output_policy, iteration)134 }135136 /// Run the command specified by `--conclude`.137 fn run_conclusion_command(
1 unmodified line
139 command: &Command<'_>,140 output_policy: &CommandOutputPolicy,141 iteration: executor::BenchmarkIteration,142 ) -> Result<Measurement> {152 let error_output = "The conclusion command terminated with a non-zero exit code. \153 Append ' || true' to the command if you are sure that this can be ignored.";154155 self.run_intermediate_command(command, error_output, output_policy, iteration)143 self.run_intermediate_command(command, "conclusion", output_policy, iteration)144 }145146 fn validate_measurement(&self, measurement: &Measurement) -> Result<()> {147 if self.options.skip_unavailable_metrics {
316 unmodified lines
modified:src/cli.rs+6 added-5 removed
234 unmodified lines
235 .action(ArgAction::Set)236 .value_name("SHELL")237 .overrides_with("shell")238 .value_hint(ValueHint::CommandString)239 .help("Set the shell to use for executing commands (default: none). This can be the \240 name or the path to the shell executable, or a full command line \239 .help("Set the shell to use for executing benchmarked commands, including warmup runs \240 (default: none). This can be the name or the path to the shell executable, or a full command line \241 like \"bash --norc\". It can also be set to \"default\" to explicitly select \242 the platform shell (sh on Unix, cmd.exe on Windows). It can also be set to \243 \"none\" to disable the shell. In this case, commands will be executed \243 \"none\" to disable the shell. In this case, benchmarked commands will be executed \244 directly. They can still have arguments, but more complex things like \245 \"sleep 0.1; sleep 0.2\" are not possible without a shell. This option also \246 applies to setup, prepare, conclude, and cleanup commands.")245 \"sleep 0.1; sleep 0.2\" are not possible without a shell. Setup, prepare, conclude, \246 and cleanup commands always use a shell: the selected shell, or the platform \247 shell when this option is omitted or set to \"none\".")248 )249 .arg(250 Arg::new("default-shell")251 .short('S')
172 unmodified lines
modified:tests/integration_tests.rs+19 added-19 removed
273 unmodified lines
274 .arg("some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")275 .assert()276 .failure()277 .stderr(predicate::str::contains(278 "Command terminated with non-zero exit code",278 "Command 'some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577' terminated with non-zero exit code",279 ));280}281282#[test]
14 unmodified lines
297fn fails_for_failing_command_without_shell() {298 hyperfine()299 .arg("--shell=none")300 .arg("--runs=1")301 .arg("false")301 .arg("--command-name=named benchmark")302 .args(["--parameter-list", "status", "0,1"])303 .arg("test {status} -eq 0")304 .assert()305 .failure()306 .stderr(predicate::str::contains(305 "Command terminated with non-zero exit code",306 ));307 "Command 'test 1 -eq 0' terminated with non-zero exit code 1 in the first benchmark run.",308 ))309 .stderr(predicate::str::contains("--ignore-failure"));310}311312#[test]313fn fails_for_unknown_setup_command() {
3 unmodified lines
317 .arg("--setup=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")318 .arg("echo test")319 .assert()320 .failure()318 .stderr(predicate::str::contains(319 "The setup command terminated with a non-zero exit code.",320 ));321 .stderr(predicate::str::contains("The setup command failed:"));322}323324#[test]325fn fails_for_unknown_cleanup_command() {
3 unmodified lines
329 .arg("--cleanup=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")330 .arg("echo test")331 .assert()332 .failure()332 .stderr(predicate::str::contains(333 "The cleanup command terminated with a non-zero exit code.",334 ));333 .stderr(predicate::str::contains("The cleanup command failed:"));334}335336#[test]337fn fails_for_unknown_prepare_command() {
2 unmodified lines
340 .arg("--prepare=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")341 .arg("echo test")342 .assert()343 .failure()345 .stderr(predicate::str::contains(346 "The preparation command terminated with a non-zero exit code.",347 ));344 .stderr(predicate::str::contains("The preparation command failed:"));345}346347#[test]348fn fails_for_unknown_conclude_command() {
2 unmodified lines
351 .arg("--conclude=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")352 .arg("echo test")353 .assert()354 .failure()358 .stderr(predicate::str::contains(359 "The conclusion command terminated with a non-zero exit code.",360 ));355 .stderr(predicate::str::contains("The conclusion command failed:"));356}357358#[cfg(unix)]359#[test]
2 unmodified lines
362 .arg("false")363 .assert()364 .failure()365 .stderr(predicate::str::contains(371 "Command terminated with non-zero exit code",366 "Command 'false' terminated with non-zero exit code",367 ));368369 hyperfine()370 .arg("--runs=1")
23 unmodified lines
394 .arg("exit 2")395 .assert()396 .failure()397 .stderr(predicate::str::contains(403 "Command terminated with non-zero exit code 2",398 "Command 'exit 2' terminated with non-zero exit code 2",399 ));400}401402#[cfg(unix)]
32 unmodified lines
435 .arg("exit 4")436 .assert()437 .failure()438 .stderr(predicate::str::contains(444 "Command terminated with non-zero exit code 4",439 "Command 'exit 4' terminated with non-zero exit code 4",440 ));441}442443#[cfg(unix)]
27 unmodified lines
471 .arg("--runs=1")472 .arg("--show-output")473 .arg("--shell")474 .arg("echo 'custom_shell' '--shell-arg'")475 .arg("--setup=echo setup")476 .arg("--prepare=echo prepare")477 .arg("--conclude=echo conclude")478 .arg("--cleanup=echo cleanup")479 .arg("echo benchmark")480 .assert()481 .success()482 .stdout(predicate::str::contains("custom_shell --shell-arg").count(5))483 .stdout(484 predicate::str::contains("custom_shell --shell-arg -c echo benchmark").or(485 predicate::str::contains("custom_shell --shell-arg /C echo benchmark"),486 ),
788 unmodified lines
modified:README.md+5 added-4 removed
106 unmodified lines
107```108109### Intermediate shell110111By default, commands are executed directly, without an intermediate shell (`--shell=none`).111By default, benchmarked commands, including warmup runs, are executed directly, without an intermediate shell (`--shell=none`).112Arguments are split using shell-like quoting, so quoted arguments containing spaces are supported.113Shell syntax such as pipes, redirections, environment-variable expansion, `*`, and `~` is not interpreted.114This avoids shell startup overhead and the noise from correcting for it, especially for fast commands115(< 5 ms).
8 unmodified lines
124```sh125hyperfine --shell zsh 'for i in {1..10000}; do echo test; done'126```127128The shell setting applies to all commands, including `--setup`, `--prepare`, `--conclude`, and `--cleanup`.129If any of these commands need shell syntax, enable a shell explicitly.128The `--setup`, `--prepare`, `--conclude`, and `--cleanup` commands always run through a shell.129They use the shell selected by `--shell`, or the platform shell (`sh` on Unix, `cmd.exe` on Windows)130when `--shell` is omitted or set to `none`.131131When a shell is enabled, hyperfine *corrects for the shell spawning time*. It runs the shell with an132When benchmarked commands use a shell, hyperfine *corrects for the shell spawning time*. It runs the shell with an133empty command multiple times to measure its startup time, then subtracts this time from each134time measurement.135136
313 unmodified lines