Skip to content
Myr

Multiple output policies

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 2899deb · Browse files · 7 files+97 added−47 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+97 added−47 removed

  • other:+97 added−47 removed

7 files+97 added−47 removed

modified:doc/hyperfine.1+5 added
288 unmodified lines
289Don't redirect the output at all (same as \&'\-\-show\-output').290.IP "<FILE>"291Write the output to the given file.292.RE293.IP294This option can be specified once for all commands or multiple times,295once for each command. Note: If you want to log the output of each and296every iteration, you can use a shell redirection and the $HYPERFINE_ITERATION297environment variable: 'my-command > output-${HYPERFINE_ITERATION}.log'298.HP299\fB\-\-input\fR \fIWHERE\fP300.IP301Control where the input of the benchmark comes from.
70 unmodified lines
modified:src/benchmark/executor.rs+7 added-2 removed
37 unmodified lines
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 to
69 unmodified lines
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,125 &self.options.command_output_policy,127 output_policy,128 &command.get_command_line(),129 )?;130131 Ok((
36 unmodified lines
168 &self,169 command: &Command<'_>,170 iteration: BenchmarkIteration,171 command_failure_action: Option<CmdFailureAction>,172 output_policy: &CommandOutputPolicy,173 ) -> Result<(TimingResult, ExitStatus)> {174 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");175 let mut command_builder = self.shell.command();176 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });
10 unmodified lines
187 command_builder,188 iteration,189 command_failure_action.unwrap_or(self.options.command_failure_action),190 &self.options.command_input_policy,188 &self.options.command_output_policy,191 output_policy,192 &command.get_command_line(),193 )?;194195 // Subtract shell spawning time
35 unmodified lines
231 let res = self.run_command_and_measure(232 &Command::new(None, ""),233 BenchmarkIteration::NonBenchmarkRun,234 None,235 &CommandOutputPolicy::Null,236 );237238 match res {239 Err(_) => {
63 unmodified lines
303 &self,304 command: &Command<'_>,305 _iteration: BenchmarkIteration,306 _command_failure_action: Option<CmdFailureAction>,307 _output_policy: &CommandOutputPolicy,308 ) -> Result<(TimingResult, ExitStatus)> {309 #[cfg(unix)]310 let status = {311 use std::os::unix::process::ExitStatusExt;
35 unmodified lines
modified:src/benchmark/mod.rs+31 added-11 removed
6 unmodified lines
7use std::cmp;89use crate::benchmark::executor::BenchmarkIteration;10use crate::command::Command;11use crate::options::{CmdFailureAction, ExecutorKind, Options, OutputStyleOption};11use crate::options::{12 CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,13};14use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};15use crate::output::format::{format_duration, format_duration_unit};16use crate::output::progress_bar::get_progress_bar;17use crate::output::warnings::{OutlierWarningOptions, Warnings};
39 unmodified lines
57 fn run_intermediate_command(58 &self,59 command: &Command<'_>,60 error_output: &'static str,61 output_policy: &CommandOutputPolicy,62 ) -> Result<TimingResult> {63 self.executor64 .run_command_and_measure(65 command,66 executor::BenchmarkIteration::NonBenchmarkRun,67 Some(CmdFailureAction::RaiseError),68 output_policy,69 )70 .map(|r| r.0)71 .map_err(|_| anyhow!(error_output))72 }
1 unmodified line
74 /// Run the command specified by `--setup`.75 fn run_setup_command(76 &self,77 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,78 output_policy: &CommandOutputPolicy,79 ) -> Result<TimingResult> {80 let command = self81 .options82 .setup_command
3 unmodified lines
86 let error_output = "The setup command terminated with a non-zero exit code. \87 Append ' || true' to the command if you are sure that this can be ignored.";8889 Ok(command85 .map(|cmd| self.run_intermediate_command(&cmd, error_output))90 .map(|cmd| self.run_intermediate_command(&cmd, error_output, output_policy))91 .transpose()?92 .unwrap_or_default())93 }9495 /// Run the command specified by `--cleanup`.96 fn run_cleanup_command(97 &self,98 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,99 output_policy: &CommandOutputPolicy,100 ) -> Result<TimingResult> {101 let command = self102 .options103 .cleanup_command
3 unmodified lines
107 let error_output = "The cleanup command terminated with a non-zero exit code. \108 Append ' || true' to the command if you are sure that this can be ignored.";109110 Ok(command105 .map(|cmd| self.run_intermediate_command(&cmd, error_output))111 .map(|cmd| self.run_intermediate_command(&cmd, error_output, output_policy))112 .transpose()?113 .unwrap_or_default())114 }115116 /// Run the command specified by `--prepare`.111 fn run_preparation_command(&self, command: &Command<'_>) -> Result<TimingResult> {117 fn run_preparation_command(118 &self,119 command: &Command<'_>,120 output_policy: &CommandOutputPolicy,121 ) -> Result<TimingResult> {122 let error_output = "The preparation command terminated with a non-zero exit code. \123 Append ' || true' to the command if you are sure that this can be ignored.";124115 self.run_intermediate_command(command, error_output)125 self.run_intermediate_command(command, error_output, output_policy)126 }127128 /// Run the command specified by `--conclude`.119 fn run_conclusion_command(&self, command: &Command<'_>) -> Result<TimingResult> {129 fn run_conclusion_command(130 &self,131 command: &Command<'_>,132 output_policy: &CommandOutputPolicy,133 ) -> Result<TimingResult> {134 let error_output = "The conclusion command terminated with a non-zero exit code. \135 Append ' || true' to the command if you are sure that this can be ignored.";136123 self.run_intermediate_command(command, error_output)137 self.run_intermediate_command(command, error_output, output_policy)138 }139140 /// Run the benchmark for a single command141 pub fn run(&self) -> Result<BenchmarkResult> {
11 unmodified lines
153 let mut times_system: Vec<Second> = vec![];154 let mut exit_codes: Vec<Option<i32>> = vec![];155 let mut all_succeeded = true;156157 let output_policy = &self.options.command_output_policies[self.number];158159 let preparation_command = self.options.preparation_command.as_ref().map(|values| {160 let preparation_command = if values.len() == 1 {161 &values[0]162 } else {
4 unmodified lines
167 preparation_command,168 self.command.get_parameters().iter().cloned(),169 )170 });171172 let run_preparation_command = || {173 preparation_command174 .as_ref()158 .map(|cmd| self.run_preparation_command(cmd))175 .map(|cmd| self.run_preparation_command(cmd, output_policy))176 .transpose()177 };178179 let conclusion_command = self.options.conclusion_command.as_ref().map(|values| {
10 unmodified lines
190 });191 let run_conclusion_command = || {192 conclusion_command193 .as_ref()177 .map(|cmd| self.run_conclusion_command(cmd))194 .map(|cmd| self.run_conclusion_command(cmd, output_policy))195 .transpose()196 };197181 self.run_setup_command(self.command.get_parameters().iter().cloned())?;198 self.run_setup_command(self.command.get_parameters().iter().cloned(), output_policy)?;199200 // Warmup phase201 if self.options.warmup_count > 0 {202 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {
11 unmodified lines
214 let _ = self.executor.run_command_and_measure(215 self.command,216 BenchmarkIteration::Warmup(i),217 None,218 output_policy,219 )?;220 let _ = run_conclusion_command()?;221 if let Some(bar) = progress_bar.as_ref() {222 bar.inc(1)
23 unmodified lines
246 let (res, status) = self.executor.run_command_and_measure(247 self.command,248 BenchmarkIteration::Benchmark(0),249 None,250 output_policy,251 )?;252 let success = status.success();253254 let conclusion_result = run_conclusion_command()?;
52 unmodified lines
307 let (res, status) = self.executor.run_command_and_measure(308 self.command,309 BenchmarkIteration::Benchmark(i + 1),310 None,311 output_policy,312 )?;313 let success = status.success();314315 times_real.push(res.time_real);
121 unmodified lines
437 if self.options.output_style != OutputStyleOption::Disabled {438 println!(" ");439 }440421 self.run_cleanup_command(self.command.get_parameters().iter().cloned())?;441 self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;442443 Ok(BenchmarkResult {444 command: self.command.get_name(),445 command_with_unused_parameters: self.command.get_name_with_unused_parameters(),
18 unmodified lines
modified:src/cli.rs+6 added-2 removed
325 unmodified lines
326 .arg(327 Arg::new("output")328 .long("output")329 .conflicts_with("show-output")330 .action(ArgAction::Set)330 .action(ArgAction::Append)331 .value_name("WHERE")332 .help(333 "Control where the output of the benchmark is redirected. Note \334 that some programs like 'grep' detect when standard output is \
7 unmodified lines
342 pipe: Feed the output through a pipe before discarding it.\n\343 \n \344 inherit: Don't redirect the output at all (same as '--show-output').\n\345 \n \346 <FILE>: Write the output to the given file.",346 <FILE>: Write the output to the given file.\n\n\347 This option can be specified once for all commands or multiple times, once for \348 each command. Note: If you want to log the output of each and every iteration, \349 you can use a shell redirection and the '$HYPERFINE_ITERATION' environment variable:\n \350 hyperfine 'my-command > output-${HYPERFINE_ITERATION}.log'\n\n",351 ),352 )353 .arg(354 Arg::new("input")
46 unmodified lines
modified:src/command.rs+2 added-2 removed
249 unmodified lines
250 pub fn iter(&self) -> impl Iterator<Item = &Command<'a>> {251 self.0.iter()252 }253254 pub fn num_commands(&self) -> usize {255 self.0.len()254 pub fn num_commands(&self, has_reference_command: bool) -> usize {255 self.0.len() + if has_reference_command { 1 } else { 0 }256 }257258 /// Finds all the strings that appear multiple times in the input iterator, returning them in259 /// sorted order. If no string appears more than once, the result is an empty vector.
303 unmodified lines
modified:src/main.rs+1 added-1 removed
30 unmodified lines
31 #[cfg(windows)]32 colored::control::set_virtual_terminal(true).unwrap();3334 let cli_arguments = get_cli_arguments(env::args_os());35 let options = Options::from_cli_arguments(&cli_arguments)?;35 let mut options = Options::from_cli_arguments(&cli_arguments)?;36 let commands = Commands::from_cli_arguments(&cli_arguments)?;37 let export_manager = ExportManager::from_cli_arguments(&cli_arguments, options.time_unit)?;3839 options.validate_against_command_list(&commands)?;
18 unmodified lines
modified:src/options.rs+45 added-29 removed
232 unmodified lines
233234 /// Where input to the benchmarked command comes from235 pub command_input_policy: CommandInputPolicy,236237 /// What to do with the output of the benchmarked command238 pub command_output_policy: CommandOutputPolicy,237 /// What to do with the output of the benchmarked commands238 pub command_output_policies: Vec<CommandOutputPolicy>,239240 /// Which time unit to use when displaying results241 pub time_unit: Option<Unit>,242}
13 unmodified lines
256 output_style: OutputStyleOption::Full,257 sort_order_speed_comparison: SortOrder::MeanTime,258 sort_order_exports: SortOrder::Command,259 executor_kind: ExecutorKind::default(),260 command_output_policy: CommandOutputPolicy::Null,260 command_output_policies: vec![CommandOutputPolicy::Null],261 time_unit: None,262 command_input_policy: CommandInputPolicy::Null,263 }264 }
54 unmodified lines
319 .map(|values| values.map(String::from).collect::<Vec<String>>());320321 options.cleanup_command = matches.get_one::<String>("cleanup").map(String::from);322323 options.command_output_policies = if matches.get_flag("show-output") {324 vec![CommandOutputPolicy::Inherit]323 options.command_output_policy = if matches.get_flag("show-output") {324 CommandOutputPolicy::Inherit325 } else if let Some(output) = matches.get_one::<String>("output").map(|s| s.as_str()) {326 match output {327 "null" => CommandOutputPolicy::Null,328 "pipe" => CommandOutputPolicy::Pipe,329 "inherit" => CommandOutputPolicy::Inherit,330 arg => {331 let path = PathBuf::from(arg);332 if path.components().count() <= 1 {333 return Err(OptionsError::UnknownOutputPolicy(arg.to_string()));325 } else if let Some(output_values) = matches.get_many::<String>("output") {326 let mut policies = vec![];327 for value in output_values {328 let policy = match value.as_str() {329 "null" => CommandOutputPolicy::Null,330 "pipe" => CommandOutputPolicy::Pipe,331 "inherit" => CommandOutputPolicy::Inherit,332 arg => {333 let path = PathBuf::from(arg);334 if path.components().count() <= 1 {335 return Err(OptionsError::UnknownOutputPolicy(arg.to_string()));336 }337 CommandOutputPolicy::File(path)338 }335 CommandOutputPolicy::File(path)336 }339 };340 policies.push(policy);341 }342 policies343 } else {339 CommandOutputPolicy::Null344 vec![CommandOutputPolicy::Null]345 };346347 options.output_style = match matches.get_one::<String>("style").map(|s| s.as_str()) {348 Some("full") => OutputStyleOption::Full,
1 unmodified line
350 Some("nocolor") => OutputStyleOption::NoColor,351 Some("color") => OutputStyleOption::Color,352 Some("none") => OutputStyleOption::Disabled,353 _ => {349 if options.command_output_policy == CommandOutputPolicy::Inherit354 if options355 .command_output_policies356 .iter()357 .any(|policy| *policy == CommandOutputPolicy::Inherit)358 || !io::stdout().is_terminal()359 {360 OutputStyleOption::Basic361 } else if env::var_os("TERM")
81 unmodified lines
443444 Ok(options)445 }446439 pub fn validate_against_command_list(&self, commands: &Commands) -> Result<()> {440 let num_commands = commands.num_commands()441 + if self.reference_command.is_some() {442 1443 } else {444 0445 };447 pub fn validate_against_command_list(&mut self, commands: &Commands) -> Result<()> {448 let has_reference_command = self.reference_command.is_some();449 let num_commands = commands.num_commands(has_reference_command);450451 if let Some(preparation_command) = &self.preparation_command {452 ensure!(453 preparation_command.len() <= 1 || num_commands == preparation_command.len(),449 "The '--prepare' option has to be provided just once or N times, where N is the \450 number of benchmark commands including a potential reference."454 "The '--prepare' option has to be provided just once or N times, where N={num_commands} is the \455 number of benchmark commands (including a potential reference)."456 );457 }458459 if let Some(conclusion_command) = &self.conclusion_command {460 ensure!(461 conclusion_command.len() <= 1 || num_commands == conclusion_command.len(),457 "The '--conclude' option has to be provided just once or N times, where N is the \458 number of benchmark commands including a potential reference."462 "The '--conclude' option has to be provided just once or N times, where N={num_commands} is the \463 number of benchmark commands (including a potential reference)."464 );465 }466467 if self.command_output_policies.len() == 1 {468 self.command_output_policies =469 vec![self.command_output_policies[0].clone(); num_commands];470 } else {471 ensure!(472 self.command_output_policies.len() == num_commands,473 "The '--output' option has to be provided just once or N times, where N={num_commands} is the \474 number of benchmark commands (including a potential reference)."475 );476 }477478 Ok(())479 }480}481
43 unmodified lines