Files
hyperfine/src/hyperfine/benchmark.rs
T

237 lines
6.6 KiB
Rust
Raw Normal View History

2018-01-14 20:14:10 +01:00
use std::io;
use std::process::{Command, Stdio};
use std::time::Instant;
2018-01-16 21:26:14 +01:00
use ansi_term::Colour::{Cyan, Green, Purple, White, Yellow};
2018-01-14 21:07:00 +01:00
use statistical::{mean, standard_deviation};
2018-01-14 20:14:10 +01:00
2018-01-14 21:43:29 +01:00
use hyperfine::internal::{get_progress_bar, max, min, HyperfineOptions, Second, Warnings,
2018-01-18 18:39:17 +01:00
MIN_EXECUTION_TIME, CmdFailureAction};
use hyperfine::format::{format_duration, format_duration_unit, Unit};
2018-01-14 20:14:10 +01:00
/// Results from timing a single shell command
pub struct TimingResult {
/// Execution time in seconds
2018-01-14 21:07:00 +01:00
pub execution_time: Second,
2018-01-14 20:14:10 +01:00
/// True if the command finished with exit code zero
pub success: bool,
}
impl TimingResult {
2018-01-14 21:07:00 +01:00
fn new(execution_time: Second, success: bool) -> TimingResult {
2018-01-14 20:14:10 +01:00
TimingResult {
2018-01-14 21:07:00 +01:00
execution_time,
2018-01-14 20:14:10 +01:00
success,
}
}
}
/// Run the given shell command and measure the execution time
2018-01-14 21:07:00 +01:00
pub fn time_shell_command(
shell_cmd: &str,
2018-01-18 18:39:17 +01:00
failure_action: CmdFailureAction,
2018-01-14 21:07:00 +01:00
shell_spawning_time: Option<Second>,
) -> io::Result<TimingResult> {
2018-01-14 20:14:10 +01:00
let start = Instant::now();
let status = Command::new("sh")
.arg("-c")
.arg(shell_cmd)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()?;
2018-01-18 18:39:17 +01:00
if failure_action == CmdFailureAction::RaiseError && !status.success() {
2018-01-14 20:14:10 +01:00
return Err(io::Error::new(
io::ErrorKind::Other,
"Command terminated with non-zero exit code. \
Use the '-i'/'--ignore-failure' option if you want to ignore this.",
));
}
let duration = start.elapsed();
2018-01-14 21:07:00 +01:00
let execution_time = duration.as_secs() as f64 + duration.subsec_nanos() as f64 * 1e-9;
2018-01-14 20:14:10 +01:00
2018-01-14 21:07:00 +01:00
// Correct for shell spawning time
let execution_time_corrected = if let Some(spawning_time) = shell_spawning_time {
if execution_time < spawning_time {
0.0
} else {
execution_time - spawning_time
}
} else {
execution_time
};
Ok(TimingResult::new(
execution_time_corrected,
status.success(),
))
2018-01-14 20:14:10 +01:00
}
/// Measure the average shell spawning time
pub fn mean_shell_spawning_time() -> io::Result<Second> {
const COUNT: u64 = 200;
let bar = get_progress_bar(COUNT, "Measuring shell spawning time");
let mut times: Vec<Second> = vec![];
for _ in 0..COUNT {
2018-01-14 21:07:00 +01:00
// Just run the shell without any command
2018-01-18 18:39:17 +01:00
let res = time_shell_command("", CmdFailureAction::RaiseError, None);
2018-01-14 20:14:10 +01:00
match res {
Err(_) => {
return Err(io::Error::new(
io::ErrorKind::Other,
"Could not measure shell execution time. \
Make sure you can run 'sh -c \"\"'.",
))
}
Ok(r) => {
2018-01-14 21:07:00 +01:00
times.push(r.execution_time);
2018-01-14 20:14:10 +01:00
}
}
bar.inc(1);
}
bar.finish_and_clear();
2018-01-14 21:07:00 +01:00
Ok(mean(&times))
2018-01-14 20:14:10 +01:00
}
/// Run the benchmark for a single shell command
pub fn run_benchmark(
num: usize,
cmd: &str,
shell_spawning_time: Second,
options: &HyperfineOptions,
) -> io::Result<()> {
println!(
"{}{}: {}",
White.bold().paint("Benchmark #"),
White.bold().paint((num + 1).to_string()),
2018-01-14 22:01:22 +01:00
cmd
2018-01-14 20:14:10 +01:00
);
println!();
2018-01-14 21:07:00 +01:00
let mut execution_times: Vec<Second> = vec![];
let mut all_succeeded = true;
2018-01-14 20:14:10 +01:00
// Warmup phase
if options.warmup_count > 0 {
let bar = get_progress_bar(options.warmup_count, "Performing warmup runs");
for _ in 0..options.warmup_count {
2018-01-18 18:39:17 +01:00
let _ = time_shell_command(cmd, options.failure_action, None)?;
2018-01-14 20:14:10 +01:00
bar.inc(1);
}
bar.finish_and_clear();
}
// Set up progress bar (and spinner for initial measurement)
let bar = get_progress_bar(options.min_runs, "Initial time measurement");
2018-01-18 18:13:12 +01:00
// Run init / cleanup command
let run_preparation_command = || {
if let Some(ref preparation_command) = options.preparation_command {
2018-01-18 18:39:17 +01:00
let _ = time_shell_command(preparation_command, options.failure_action, None);
2018-01-16 21:26:14 +01:00
}
};
2018-01-18 18:13:12 +01:00
run_preparation_command();
2018-01-16 21:26:14 +01:00
2018-01-14 20:14:10 +01:00
// Initial timing run
2018-01-18 18:39:17 +01:00
let res = time_shell_command(cmd, options.failure_action, Some(shell_spawning_time))?;
2018-01-14 20:14:10 +01:00
// Determine number of benchmark runs
2018-01-14 21:07:00 +01:00
let runs_in_min_time =
(options.min_time_sec / (res.execution_time + shell_spawning_time)) as u64;
2018-01-14 20:14:10 +01:00
let count = if runs_in_min_time >= options.min_runs {
runs_in_min_time
} else {
options.min_runs
};
let count_remaining = count - 1;
// Save the first result
2018-01-14 21:07:00 +01:00
execution_times.push(res.execution_time);
all_succeeded = all_succeeded && res.success;
2018-01-14 20:14:10 +01:00
// Re-configure the progress bar
bar.set_length(count_remaining);
// Gather statistics
for _ in 0..count_remaining {
2018-01-18 18:13:12 +01:00
run_preparation_command();
2018-01-16 21:26:14 +01:00
2018-01-14 20:14:10 +01:00
let msg = {
2018-01-14 21:07:00 +01:00
let mean = format_duration(mean(&execution_times), Unit::Auto);
format!("Current estimate: {}", Green.paint(mean))
2018-01-14 20:14:10 +01:00
};
bar.set_message(&msg);
2018-01-18 18:39:17 +01:00
let res = time_shell_command(cmd, options.failure_action, Some(shell_spawning_time))?;
2018-01-14 21:07:00 +01:00
execution_times.push(res.execution_time);
all_succeeded = all_succeeded && res.success;
2018-01-14 20:14:10 +01:00
bar.inc(1);
}
bar.finish_and_clear();
// Compute statistical quantities
2018-01-14 21:43:29 +01:00
let t_mean = mean(&execution_times);
let t_stddev = standard_deviation(&execution_times, Some(t_mean));
let t_min = min(&execution_times);
let t_max = max(&execution_times);
2018-01-14 20:14:10 +01:00
// Formatting and console output
2018-01-14 21:43:29 +01:00
let (mean_str, unit_mean) = format_duration_unit(t_mean, Unit::Auto);
let stddev_str = format_duration(t_stddev, unit_mean);
let min_str = format_duration(t_min, unit_mean);
let max_str = format_duration(t_max, unit_mean);
2018-01-14 20:14:10 +01:00
2018-01-14 21:43:29 +01:00
println!(
2018-01-14 22:01:22 +01:00
" Time ({} ± {}): {} ± {}",
Green.bold().paint("mean"),
Green.paint("σ"),
Green.bold().paint(mean_str),
Green.paint(stddev_str)
2018-01-14 21:43:29 +01:00
);
2018-01-14 22:07:19 +01:00
println!(" ");
2018-01-14 21:43:29 +01:00
println!(
2018-01-14 22:01:22 +01:00
" Range ({} … {}): {} … {}",
Cyan.paint("min"),
Purple.paint("max"),
Cyan.paint(min_str),
Purple.paint(max_str)
2018-01-14 21:43:29 +01:00
);
2018-01-14 20:14:10 +01:00
// Warnings
let mut warnings = vec![];
// Check execution time
2018-01-14 21:07:00 +01:00
if execution_times.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);
}
if warnings.len() > 0 {
2018-01-14 22:07:19 +01:00
eprintln!(" ");
2018-01-14 20:14:10 +01:00
for warning in &warnings {
eprintln!(" {}: {}", Yellow.paint("Warning"), warning);
}
}
2018-01-14 22:07:19 +01:00
println!(" ");
2018-01-14 20:14:10 +01:00
Ok(())
}