Files
hyperfine/src/hyperfine/benchmark.rs
T

484 lines
14 KiB
Rust
Raw Normal View History

use std::cmp;
2018-01-14 20:14:10 +01:00
use std::io;
2021-02-28 10:22:21 +01:00
use std::process::{ExitStatus, Stdio};
2018-01-14 20:14:10 +01:00
2018-01-24 20:12:17 +01:00
use colored::*;
use statistical::{mean, median, standard_deviation};
2018-01-14 20:14:10 +01:00
2021-08-22 19:08:08 +02:00
use crate::hyperfine::benchmark_result::BenchmarkResult;
2021-08-22 17:52:55 +02:00
use crate::hyperfine::command::Command;
2019-05-07 11:55:38 +02:00
use crate::hyperfine::format::{format_duration, format_duration_unit};
use crate::hyperfine::internal::{get_progress_bar, max, min, MIN_EXECUTION_TIME};
2021-08-22 17:53:08 +02:00
use crate::hyperfine::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};
2019-05-07 11:55:38 +02:00
use crate::hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};
use crate::hyperfine::shell::execute_and_time;
use crate::hyperfine::timer::wallclocktimer::WallClockTimer;
use crate::hyperfine::timer::{TimerStart, TimerStop};
use crate::hyperfine::units::Second;
use crate::hyperfine::warnings::Warnings;
2018-01-14 20:14:10 +01:00
/// Results from timing a single shell command
2018-02-13 12:19:52 +08:00
#[derive(Debug, Default, Copy, Clone)]
2018-01-14 20:14:10 +01:00
pub struct TimingResult {
2018-01-19 08:44:33 +01:00
/// Wall clock time
pub time_real: Second,
2018-01-14 20:14:10 +01:00
2018-01-19 08:44:33 +01:00
/// Time spent in user mode
pub time_user: Second,
/// Time spent in kernel mode
pub time_system: Second,
2018-01-14 20:14:10 +01:00
}
2018-01-19 08:44:33 +01:00
/// Correct for shell spawning time
fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {
if time < shell_spawning_time {
0.0
} else {
time - shell_spawning_time
2018-01-14 20:14:10 +01:00
}
}
/// Run the given shell command and measure the execution time
2018-01-14 21:07:00 +01:00
pub fn time_shell_command(
2018-10-30 19:30:17 -07:00
shell: &str,
2019-05-07 11:55:38 +02:00
command: &Command<'_>,
2018-05-21 21:04:30 +02:00
show_output: bool,
2018-01-18 18:39:17 +01:00
failure_action: CmdFailureAction,
2018-01-19 08:44:33 +01:00
shell_spawning_time: Option<TimingResult>,
2021-02-28 10:22:21 +01:00
) -> io::Result<(TimingResult, ExitStatus)> {
2018-05-21 21:04:30 +02:00
let (stdout, stderr) = if show_output {
(Stdio::inherit(), Stdio::inherit())
} else {
2018-05-21 21:04:30 +02:00
(Stdio::null(), Stdio::null())
};
let wallclock_timer = WallClockTimer::start();
2018-10-30 19:30:17 -07:00
let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;
let mut time_real = wallclock_timer.stop();
2018-02-05 18:22:59 -05:00
let mut time_user = result.user_time;
let mut time_system = result.system_time;
2018-01-14 20:14:10 +01:00
2018-02-05 18:22:59 -05:00
if failure_action == CmdFailureAction::RaiseError && !result.status.success() {
2018-01-14 20:14:10 +01:00
return Err(io::Error::new(
io::ErrorKind::Other,
2020-10-25 19:04:17 +01:00
format!(
"{}. \
Use the '-i'/'--ignore-failure' option if you want to ignore this. \
Alternatively, use the '--show-output' option to debug what went wrong.",
result.status.code().map_or(
"The process has been terminated by a signal".into(),
|c| format!("Command terminated with non-zero exit code: {}", c)
)
),
2018-01-14 20:14:10 +01:00
));
}
2018-01-14 21:07:00 +01:00
// Correct for shell spawning time
2018-01-19 08:44:33 +01:00
if let Some(spawning_time) = shell_spawning_time {
time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);
2018-02-01 18:27:34 -05:00
time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);
time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);
2018-01-19 08:44:33 +01:00
}
2018-01-14 21:07:00 +01:00
2018-01-19 08:44:33 +01:00
Ok((
TimingResult {
time_real,
time_user,
time_system,
},
2021-02-28 10:22:21 +01:00
result.status,
2018-01-14 21:07:00 +01:00
))
2018-01-14 20:14:10 +01:00
}
/// Measure the average shell spawning time
pub fn mean_shell_spawning_time(
2018-10-30 19:30:17 -07:00
shell: &str,
2019-07-13 10:38:51 +02:00
style: OutputStyleOption,
2018-05-21 21:04:30 +02:00
show_output: bool,
) -> io::Result<TimingResult> {
const COUNT: u64 = 50;
2019-10-14 00:03:29 +03:00
let progress_bar = if style != OutputStyleOption::Disabled {
Some(get_progress_bar(
COUNT,
"Measuring shell spawning time",
style,
))
} else {
None
};
2018-01-14 20:14:10 +01:00
2018-01-19 08:44:33 +01:00
let mut times_real: Vec<Second> = vec![];
let mut times_user: Vec<Second> = vec![];
let mut times_system: Vec<Second> = vec![];
2018-01-14 20:14:10 +01:00
for _ in 0..COUNT {
2018-01-14 21:07:00 +01:00
// Just run the shell without any command
let res = time_shell_command(
2018-10-30 19:30:17 -07:00
shell,
&Command::new(None, ""),
2018-05-21 21:04:30 +02:00
show_output,
CmdFailureAction::RaiseError,
None,
);
2018-01-14 20:14:10 +01:00
match res {
Err(_) => {
2018-10-30 19:30:17 -07:00
let shell_cmd = if cfg!(windows) {
format!("{} /C \"\"", shell)
} else {
format!("{} -c \"\"", shell)
};
2018-01-14 20:14:10 +01:00
return Err(io::Error::new(
2018-11-21 19:55:58 +01:00
io::ErrorKind::Other,
format!(
"Could not measure shell execution time. \
Make sure you can run '{}'.",
shell_cmd
),
));
2018-01-14 20:14:10 +01:00
}
2018-01-19 08:44:33 +01:00
Ok((r, _)) => {
times_real.push(r.time_real);
times_user.push(r.time_user);
times_system.push(r.time_system);
2018-01-14 20:14:10 +01:00
}
2019-10-14 00:03:29 +03:00
}
2019-10-15 15:34:58 +03:00
2021-08-22 16:05:03 +02:00
if let Some(bar) = progress_bar.as_ref() {
bar.inc(1)
}
2018-01-14 20:14:10 +01:00
}
2021-08-22 16:05:03 +02:00
if let Some(bar) = progress_bar.as_ref() {
bar.finish_and_clear()
}
2018-01-19 08:44:33 +01:00
Ok(TimingResult {
time_real: mean(&times_real),
time_user: mean(&times_user),
time_system: mean(&times_system),
})
2018-01-14 20:14:10 +01:00
}
fn run_intermediate_command(
2018-10-30 19:30:17 -07:00
shell: &str,
2019-05-07 11:55:38 +02:00
command: &Option<Command<'_>>,
2018-05-21 21:04:30 +02:00
show_output: bool,
error_output: &'static str,
) -> io::Result<TimingResult> {
2019-07-13 10:10:59 +02:00
if let Some(ref cmd) = command {
2018-10-30 19:30:17 -07:00
let res = time_shell_command(shell, cmd, show_output, CmdFailureAction::RaiseError, None);
2018-01-28 18:43:04 +01:00
if res.is_err() {
2019-03-29 07:59:23 +05:30
return Err(io::Error::new(io::ErrorKind::Other, error_output));
2018-01-20 15:31:50 +01:00
}
2018-02-13 12:19:52 +08:00
return res.map(|r| r.0);
2018-01-20 15:31:50 +01:00
}
2018-02-13 12:19:52 +08:00
Ok(TimingResult {
..Default::default()
})
}
/// Run the command specified by `--prepare`.
fn run_preparation_command(
shell: &str,
2019-05-07 11:55:38 +02:00
command: &Option<Command<'_>>,
show_output: bool,
) -> io::Result<TimingResult> {
let error_output = "The preparation command terminated with a non-zero exit code. \
2019-03-29 07:59:23 +05:30
Append ' || true' to the command if you are sure that this can be ignored.";
2019-03-29 07:59:23 +05:30
run_intermediate_command(shell, command, show_output, error_output)
}
/// Run the command specified by `--cleanup`.
fn run_cleanup_command(
shell: &str,
2019-05-07 11:55:38 +02:00
command: &Option<Command<'_>>,
show_output: bool,
) -> io::Result<TimingResult> {
let error_output = "The cleanup command terminated with a non-zero exit code. \
2019-03-29 07:59:23 +05:30
Append ' || true' to the command if you are sure that this can be ignored.";
2019-03-29 07:59:23 +05:30
run_intermediate_command(shell, command, show_output, error_output)
2018-01-20 15:31:50 +01:00
}
2021-02-28 10:22:21 +01:00
#[cfg(unix)]
fn extract_exit_code(status: ExitStatus) -> Option<i32> {
2021-02-28 10:22:21 +01:00
use std::os::unix::process::ExitStatusExt;
/* From the ExitStatus::code documentation:
"On Unix, this will return None if the process was terminated by a signal."
In that case, ExitStatusExt::signal should never return None.
*/
status.code().or_else(||
/* To differentiate between "normal" exit codes and signals, we are using
something similar to bash exit codes (https://tldp.org/LDP/abs/html/exitcodes.html)
by adding 128 to a signal integer value.
*/
status.signal().map(|s| 128 + s))
2021-02-28 10:22:21 +01:00
}
#[cfg(not(unix))]
fn extract_exit_code(status: ExitStatus) -> Option<i32> {
status.code()
2021-02-28 10:22:21 +01:00
}
2018-01-14 20:14:10 +01:00
/// Run the benchmark for a single shell command
pub fn run_benchmark(
num: usize,
2019-05-07 11:55:38 +02:00
cmd: &Command<'_>,
2018-01-19 08:44:33 +01:00
shell_spawning_time: TimingResult,
2018-01-14 20:14:10 +01:00
options: &HyperfineOptions,
) -> io::Result<BenchmarkResult> {
let command_name = cmd.get_name();
2019-10-14 00:03:29 +03:00
if options.output_style != OutputStyleOption::Disabled {
println!(
"{}{}: {}",
2021-05-06 22:49:02 +03:00
"Benchmark ".bold(),
(num + 1).to_string().bold(),
command_name,
);
}
2018-01-14 20:14:10 +01:00
2018-01-19 08:44:33 +01:00
let mut times_real: Vec<Second> = vec![];
let mut times_user: Vec<Second> = vec![];
let mut times_system: Vec<Second> = vec![];
let mut exit_codes: Vec<Option<i32>> = vec![];
2018-01-14 21:07:00 +01:00
let mut all_succeeded = true;
2018-01-14 20:14:10 +01:00
2019-10-14 18:51:14 +02:00
// Run init command
let prepare_cmd = options.preparation_command.as_ref().map(|values| {
let preparation_command = if values.len() == 1 {
&values[0]
} else {
&values[num]
};
Command::new_parametrized(None, preparation_command, cmd.get_parameters().clone())
2019-10-14 18:51:14 +02:00
});
2018-01-14 20:14:10 +01:00
// Warmup phase
if options.warmup_count > 0 {
2019-10-14 00:03:29 +03:00
let progress_bar = if options.output_style != OutputStyleOption::Disabled {
Some(get_progress_bar(
options.warmup_count,
"Performing warmup runs",
options.output_style,
2019-10-14 00:03:29 +03:00
))
} else {
None
};
2018-01-14 20:14:10 +01:00
for _ in 0..options.warmup_count {
2019-10-14 18:51:14 +02:00
let _ = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;
2018-11-21 19:55:58 +01:00
let _ = time_shell_command(
&options.shell,
cmd,
options.show_output,
options.failure_action,
None,
)?;
2021-08-22 16:05:03 +02:00
if let Some(bar) = progress_bar.as_ref() {
bar.inc(1)
}
}
if let Some(bar) = progress_bar.as_ref() {
bar.finish_and_clear()
2018-01-14 20:14:10 +01:00
}
}
// Set up progress bar (and spinner for initial measurement)
2019-10-14 00:03:29 +03:00
let progress_bar = if options.output_style != OutputStyleOption::Disabled {
Some(get_progress_bar(
options.runs.min,
"Initial time measurement",
options.output_style,
))
2019-10-14 00:03:29 +03:00
} else {
None
};
2018-01-14 20:14:10 +01:00
2018-10-30 19:30:17 -07:00
let prepare_res = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;
2018-01-16 21:26:14 +01:00
2018-01-14 20:14:10 +01:00
// Initial timing run
2021-02-28 10:22:21 +01:00
let (res, status) = time_shell_command(
2018-10-30 19:30:17 -07:00
&options.shell,
cmd,
2018-05-21 21:04:30 +02:00
options.show_output,
options.failure_action,
Some(shell_spawning_time),
)?;
2021-02-28 10:22:21 +01:00
let success = status.success();
2018-01-14 20:14:10 +01:00
// Determine number of benchmark runs
2018-03-03 16:29:52 +01:00
let runs_in_min_time = (options.min_time_sec
/ (res.time_real + prepare_res.time_real + shell_spawning_time.time_real))
as u64;
2018-01-14 20:14:10 +01:00
2018-09-09 21:52:58 +01:00
let count = {
let min = cmp::max(runs_in_min_time, options.runs.min);
2018-09-27 23:07:07 +02:00
options
.runs
.max
.as_ref()
2018-09-09 21:52:58 +01:00
.map(|max| cmp::min(min, *max))
.unwrap_or(min)
};
2018-01-14 20:14:10 +01:00
let count_remaining = count - 1;
// Save the first result
2018-02-13 18:37:36 +08:00
times_real.push(res.time_real);
times_user.push(res.time_user);
times_system.push(res.time_system);
2021-02-28 10:22:21 +01:00
exit_codes.push(extract_exit_code(status));
2018-01-19 08:44:33 +01:00
all_succeeded = all_succeeded && success;
2018-01-14 20:14:10 +01:00
// Re-configure the progress bar
2021-08-22 16:05:03 +02:00
if let Some(bar) = progress_bar.as_ref() {
bar.set_length(count)
}
if let Some(bar) = progress_bar.as_ref() {
bar.inc(1)
}
2018-01-14 20:14:10 +01:00
// Gather statistics
for _ in 0..count_remaining {
2018-10-30 19:30:17 -07:00
run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;
2018-01-16 21:26:14 +01:00
2018-01-14 20:14:10 +01:00
let msg = {
let mean = format_duration(mean(&times_real), options.time_unit);
2018-01-24 20:12:17 +01:00
format!("Current estimate: {}", mean.to_string().green())
2018-01-14 20:14:10 +01:00
};
2021-08-22 16:05:03 +02:00
if let Some(bar) = progress_bar.as_ref() {
bar.set_message(msg.to_owned())
}
2018-01-14 20:14:10 +01:00
2021-02-28 10:22:21 +01:00
let (res, status) = time_shell_command(
2018-10-30 19:30:17 -07:00
&options.shell,
cmd,
2018-05-21 21:04:30 +02:00
options.show_output,
options.failure_action,
Some(shell_spawning_time),
)?;
2021-02-28 10:22:21 +01:00
let success = status.success();
2018-01-14 21:07:00 +01:00
2018-02-13 18:37:36 +08:00
times_real.push(res.time_real);
times_user.push(res.time_user);
times_system.push(res.time_system);
2021-02-28 10:22:21 +01:00
exit_codes.push(extract_exit_code(status));
2018-01-19 08:44:33 +01:00
all_succeeded = all_succeeded && success;
2018-01-14 21:07:00 +01:00
2021-08-22 16:05:03 +02:00
if let Some(bar) = progress_bar.as_ref() {
bar.inc(1)
}
2018-01-14 20:14:10 +01:00
}
2021-08-22 16:05:03 +02:00
if let Some(bar) = progress_bar.as_ref() {
bar.finish_and_clear()
}
2019-10-15 15:34:58 +03:00
2018-01-14 20:14:10 +01:00
// Compute statistical quantities
2018-12-04 21:25:03 +00:00
let t_num = times_real.len();
2018-01-19 08:44:33 +01:00
let t_mean = mean(&times_real);
let t_stddev = standard_deviation(&times_real, Some(t_mean));
let t_median = median(&times_real);
2018-01-19 08:44:33 +01:00
let t_min = min(&times_real);
let t_max = max(&times_real);
let user_mean = mean(&times_user);
let system_mean = mean(&times_system);
2018-01-14 20:14:10 +01:00
// Formatting and console output
let (mean_str, time_unit) = format_duration_unit(t_mean, options.time_unit);
let stddev_str = format_duration(t_stddev, Some(time_unit));
let min_str = format_duration(t_min, Some(time_unit));
let max_str = format_duration(t_max, Some(time_unit));
2018-12-04 21:25:03 +00:00
let num_str = format!("{} runs", t_num);
2018-01-14 20:14:10 +01:00
let user_str = format_duration(user_mean, Some(time_unit));
let system_str = format_duration(system_mean, Some(time_unit));
2018-01-19 08:44:33 +01:00
2019-10-14 00:03:29 +03:00
if options.output_style != OutputStyleOption::Disabled {
println!(
" Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",
"mean".green().bold(),
"σ".green(),
mean_str.green().bold(),
stddev_str.green(),
user_str.blue(),
system_str.blue()
);
2018-01-14 21:43:29 +01:00
println!(
" Range ({} … {}): {:>8} … {:>8} {}",
"min".cyan(),
"max".purple(),
min_str.cyan(),
max_str.purple(),
num_str.dimmed()
);
}
2018-01-14 20:14:10 +01:00
// Warnings
let mut warnings = vec![];
// Check execution time
2018-01-19 08:44:33 +01:00
if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {
2018-01-14 20:14:10 +01:00
warnings.push(Warnings::FastExecutionTime);
}
// Check programm exit codes
2018-01-14 21:07:00 +01:00
if !all_succeeded {
2018-01-14 20:14:10 +01:00
warnings.push(Warnings::NonZeroExitCode);
}
2018-01-22 07:51:18 +01:00
// Run outlier detection
let scores = modified_zscores(&times_real);
if scores[0] > OUTLIER_THRESHOLD {
2018-01-24 20:12:17 +01:00
warnings.push(Warnings::SlowInitialRun(times_real[0]));
2020-10-15 22:12:56 +02:00
} else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {
2018-01-22 07:51:18 +01:00
warnings.push(Warnings::OutliersDetected);
}
2019-10-14 00:03:29 +03:00
if !warnings.is_empty() {
2018-01-14 22:07:19 +01:00
eprintln!(" ");
2018-01-14 20:14:10 +01:00
for warning in &warnings {
2018-01-24 20:12:17 +01:00
eprintln!(" {}: {}", "Warning".yellow(), warning);
2018-01-14 20:14:10 +01:00
}
}
2019-10-14 00:03:29 +03:00
if options.output_style != OutputStyleOption::Disabled {
println!(" ");
}
2018-01-14 20:14:10 +01:00
// Run cleanup command
let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {
Command::new_parametrized(None, cleanup_command, cmd.get_parameters().clone())
});
run_cleanup_command(&options.shell, &cleanup_cmd, options.show_output)?;
Ok(BenchmarkResult::new(
command_name,
t_mean,
t_stddev,
t_median,
user_mean,
system_mean,
2018-03-18 16:53:34 -04:00
t_min,
t_max,
2018-03-20 22:24:57 +01:00
times_real,
2021-02-28 10:22:21 +01:00
exit_codes,
cmd.get_parameters()
.iter()
.map(|(name, value)| ((*name).to_string(), value.to_string()))
.collect(),
))
2018-01-14 20:14:10 +01:00
}