Files
hyperfine/src/hyperfine/benchmark.rs
T

327 lines
9.6 KiB
Rust
Raw Normal View History

2018-01-14 20:14:10 +01:00
use std::io;
use std::process::ExitStatus;
2018-01-14 20:14:10 +01:00
2018-01-24 20:12:17 +01:00
use colored::*;
2018-01-14 21:07:00 +01:00
use statistical::{mean, standard_deviation};
2018-01-14 20:14:10 +01:00
use hyperfine::internal::{get_progress_bar, max, min, CmdFailureAction, HyperfineOptions,
OutputStyleOption, Second, MIN_EXECUTION_TIME};
2018-01-24 20:12:17 +01:00
use hyperfine::warnings::Warnings;
2018-01-18 18:55:27 +01:00
use hyperfine::format::{format_duration, format_duration_unit};
2018-01-22 07:51:18 +01:00
use hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};
2018-02-02 17:28:52 +01:00
use hyperfine::timer::Timer;
use hyperfine::timer::wallclocktimer::WallClockTimer;
use hyperfine::shell::run_shell_command;
2018-01-14 20:14:10 +01:00
/// Results from timing a single shell command
2018-01-19 08:44:33 +01:00
#[derive(Debug, 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(
shell_cmd: &str,
2018-01-18 18:39:17 +01:00
failure_action: CmdFailureAction,
2018-01-19 08:44:33 +01:00
shell_spawning_time: Option<TimingResult>,
) -> io::Result<(TimingResult, bool)> {
2018-02-02 17:28:52 +01:00
let wallclock_timer = WallClockTimer::start();
// let cpu_timer = CPUTimer::start();
2018-01-14 20:14:10 +01:00
let (mut time_user, mut time_system, status) = execute_and_time(shell_cmd)?;
// let status = run_shell_command(shell_cmd)?;
2018-01-14 20:14:10 +01:00
2018-02-02 17:28:52 +01:00
let mut time_real = wallclock_timer.stop();
// let (mut time_user, mut time_system) = cpu_timer.stop();
2018-01-19 08:44:33 +01:00
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.",
));
}
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,
},
2018-01-14 21:07:00 +01:00
status.success(),
))
2018-01-14 20:14:10 +01:00
}
/// Measure the average shell spawning time
pub fn mean_shell_spawning_time(style: &OutputStyleOption) -> io::Result<TimingResult> {
2018-01-14 20:14:10 +01:00
const COUNT: u64 = 200;
let progress_bar = get_progress_bar(COUNT, "Measuring shell spawning time", style);
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
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 \"\"'.",
))
}
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
}
}
2018-01-18 20:16:36 +01:00
progress_bar.inc(1);
2018-01-14 20:14:10 +01:00
}
2018-01-18 20:16:36 +01:00
progress_bar.finish_and_clear();
2018-01-14 20:14:10 +01:00
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
}
2018-01-20 15:31:50 +01:00
/// Run the command specified by `--prepare`.
fn run_preparation_command(command: &Option<String>) -> io::Result<()> {
if let &Some(ref preparation_command) = command {
let res = time_shell_command(preparation_command, CmdFailureAction::RaiseError, None);
2018-01-28 18:43:04 +01:00
if res.is_err() {
2018-01-20 15:31:50 +01:00
return Err(io::Error::new(
io::ErrorKind::Other,
"The preparation command terminated with a non-zero exit code. \
Append ' || true' to the command if you are sure that this can be ignored.",
));
}
}
Ok(())
}
2018-01-14 20:14:10 +01:00
/// Run the benchmark for a single shell command
pub fn run_benchmark(
num: usize,
cmd: &str,
2018-01-19 08:44:33 +01:00
shell_spawning_time: TimingResult,
2018-01-14 20:14:10 +01:00
options: &HyperfineOptions,
) -> io::Result<()> {
println!(
"{}{}: {}",
2018-01-24 20:12:17 +01:00
"Benchmark #".bold(),
(num + 1).to_string().bold(),
2018-01-14 22:01:22 +01:00
cmd
2018-01-14 20:14:10 +01:00
);
println!();
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 21:07:00 +01:00
let mut all_succeeded = true;
2018-01-14 20:14:10 +01:00
// Warmup phase
if options.warmup_count > 0 {
let progress_bar = get_progress_bar(
options.warmup_count,
"Performing warmup runs",
&options.output_style,
);
2018-01-14 20:14:10 +01:00
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-18 20:16:36 +01:00
progress_bar.inc(1);
2018-01-14 20:14:10 +01:00
}
2018-01-18 20:16:36 +01:00
progress_bar.finish_and_clear();
2018-01-14 20:14:10 +01:00
}
// Set up progress bar (and spinner for initial measurement)
let progress_bar = get_progress_bar(
options.min_runs,
"Initial time measurement",
&options.output_style,
);
2018-01-14 20:14:10 +01:00
2018-01-18 18:13:12 +01:00
// Run init / cleanup command
2018-01-20 15:31:50 +01:00
run_preparation_command(&options.preparation_command)?;
2018-01-16 21:26:14 +01:00
2018-01-14 20:14:10 +01:00
// Initial timing run
2018-01-19 08:44:33 +01:00
let (res, success) =
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 =
2018-01-19 08:44:33 +01:00
(options.min_time_sec / (res.time_real + shell_spawning_time.time_real)) 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-19 08:44:33 +01:00
times_real.push(res.time_real);
times_user.push(res.time_user);
times_system.push(res.time_system);
all_succeeded = all_succeeded && success;
2018-01-14 20:14:10 +01:00
// Re-configure the progress bar
2018-01-18 20:16:36 +01:00
progress_bar.set_length(count_remaining);
2018-01-14 20:14:10 +01:00
// Gather statistics
for _ in 0..count_remaining {
2018-01-20 15:31:50 +01:00
run_preparation_command(&options.preparation_command)?;
2018-01-16 21:26:14 +01:00
2018-01-14 20:14:10 +01:00
let msg = {
2018-01-19 08:44:33 +01:00
let mean = format_duration(mean(&times_real), None);
2018-01-24 20:12:17 +01:00
format!("Current estimate: {}", mean.to_string().green())
2018-01-14 20:14:10 +01:00
};
2018-01-18 20:16:36 +01:00
progress_bar.set_message(&msg);
2018-01-14 20:14:10 +01:00
2018-01-19 08:44:33 +01:00
let (res, success) =
time_shell_command(cmd, options.failure_action, Some(shell_spawning_time))?;
2018-01-14 21:07:00 +01:00
2018-01-19 08:44:33 +01:00
times_real.push(res.time_real);
times_user.push(res.time_user);
times_system.push(res.time_system);
all_succeeded = all_succeeded && success;
2018-01-14 21:07:00 +01:00
2018-01-18 20:16:36 +01:00
progress_bar.inc(1);
2018-01-14 20:14:10 +01:00
}
2018-01-18 20:16:36 +01:00
progress_bar.finish_and_clear();
2018-01-14 20:14:10 +01:00
// Compute statistical quantities
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_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
2018-01-18 18:55:27 +01:00
let (mean_str, unit_mean) = format_duration_unit(t_mean, None);
let stddev_str = format_duration(t_stddev, Some(unit_mean));
let min_str = format_duration(t_min, Some(unit_mean));
let max_str = format_duration(t_max, Some(unit_mean));
2018-01-14 20:14:10 +01:00
2018-01-19 08:44:33 +01:00
let (user_str, user_unit) = format_duration_unit(user_mean, None);
let system_str = format_duration(system_mean, Some(user_unit));
2018-02-02 17:28:52 +01:00
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 22:07:19 +01:00
println!(" ");
2018-01-14 21:43:29 +01:00
println!(
2018-01-24 20:12:17 +01:00
" Range ({} … {}): {:>8} … {:>8}",
"min".cyan(),
"max".purple(),
min_str.cyan(),
max_str.purple()
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-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]));
2018-01-22 07:51:18 +01:00
} else if scores.iter().any(|&s| s > OUTLIER_THRESHOLD) {
warnings.push(Warnings::OutliersDetected);
}
2018-01-18 20:16:36 +01: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
}
}
2018-01-14 22:07:19 +01:00
println!(" ");
2018-01-14 20:14:10 +01:00
Ok(())
}
#[cfg(windows)]
fn execute_and_time(command: &str) -> io::Result<(f64, f64, ExitStatus)> {
use hyperfine::timer::cputimer::get_process_times;
use std::os::windows::io::AsRawHandle;
let mut child = run_shell_command(command)?;
let result = child.wait()?;
let handle = child.as_raw_handle();
let (user_usec, system_usec) = get_process_times(handle);
// Temp, bypassing timer and the stop method
let user = user_usec as f64 * 1e-6;
let system = system_usec as f64 * 1e-6;
Ok((user, system, result))
}
#[cfg(not(windows))]
fn execute_and_time(command: &str) -> io::Result<(f64, f64, ExitStatus)> {
use hyperfine::timer::cputimer::CPUTimer;
let cpu_timer = CPUTimer::start();
let status = run_shell_command(command)?;
2018-02-04 20:57:06 -05:00
let (time_user, time_system) = cpu_timer.stop();
Ok((time_user, time_system, status))
}