Move functionality to scheduler
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 b658e20 · Browse files · 11 files·+560 added−560 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+560 added−560 removed
- other:+560 added−560 removed
Provenance
- Commit
dcfeede- Tree
eaf7776- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
b658e20
11 files changed+560 added−560 removed
added:src/benchmark/benchmark_result.rs+46 added
1+use std::collections::BTreeMap;2+3+use serde::Serialize;4+5+use crate::util::units::Second;6+7+/// Set of values that will be exported.8+// NOTE: `serde` is used for JSON serialization, but not for CSV serialization due to the9+// `parameters` map. Update `src/hyperfine/export/csv.rs` with new fields, as appropriate.10+#[derive(Debug, Default, Clone, Serialize, PartialEq)]11+pub struct BenchmarkResult {12+ /// The command that was run13+ pub command: String,14+15+ /// The mean run time16+ pub mean: Second,17+18+ /// The standard deviation of all run times. Not available if only one run has been performed19+ pub stddev: Option<Second>,20+21+ /// The median run time22+ pub median: Second,23+24+ /// Time spend in user space25+ pub user: Second,26+27+ /// Time spent in system space28+ pub system: Second,29+30+ /// Min time measured31+ pub min: Second,32+33+ /// Max time measured34+ pub max: Second,35+36+ /// All run time measurements37+ #[serde(skip_serializing_if = "Option::is_none")]38+ pub times: Option<Vec<Second>>,39+40+ /// All run exit codes41+ pub exit_codes: Vec<Option<i32>>,42+43+ /// Any parameter values used44+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]45+ pub parameters: BTreeMap<String, String>,46+}modified:src/benchmark/mod.rs+2 added-503 removed
1+pub mod benchmark_result;2 pub mod relative_speed;2-pub mod result;3 pub mod scheduler;4+pub mod timing_result;5 5-use std::cmp;6-use std::process::{ExitStatus, Stdio};7-8-use colored::*;9-use statistical::{mean, median, standard_deviation};10-11-use crate::benchmark::result::BenchmarkResult;12-use crate::command::Command;13-use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};14-use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};15-use crate::output::format::{format_duration, format_duration_unit};16-use crate::output::progress_bar::get_progress_bar;17-use crate::output::warnings::Warnings;18-use crate::shell::execute_and_time;19-use crate::timer::wallclocktimer::WallClockTimer;20-use crate::timer::{TimerStart, TimerStop};21-use crate::util::exit_code::extract_exit_code;22-use crate::util::min_max::{max, min};6 use crate::util::units::Second;7 25-use anyhow::{bail, Result};26-8 /// Threshold for warning about fast execution time9 pub const MIN_EXECUTION_TIME: Second = 5e-3;29-30-/// Results from timing a single command31-#[derive(Debug, Default, Copy, Clone)]32-pub struct TimingResult {33- /// Wall clock time34- pub time_real: Second,35-36- /// Time spent in user mode37- pub time_user: Second,38-39- /// Time spent in kernel mode40- pub time_system: Second,41-}42-43-/// Correct for shell spawning time44-fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {45- if time < shell_spawning_time {46- 0.047- } else {48- time - shell_spawning_time49- }50-}51-52-/// Run the given shell command and measure the execution time53-pub fn time_shell_command(54- shell: &Shell,55- command: &Command<'_>,56- command_output_policy: CommandOutputPolicy,57- failure_action: CmdFailureAction,58- shell_spawning_time: Option<TimingResult>,59-) -> Result<(TimingResult, ExitStatus)> {60- let (stdout, stderr) = match command_output_policy {61- CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),62- CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),63- };64-65- let wallclock_timer = WallClockTimer::start();66- let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;67- let mut time_real = wallclock_timer.stop();68-69- let mut time_user = result.user_time;70- let mut time_system = result.system_time;71-72- if failure_action == CmdFailureAction::RaiseError && !result.status.success() {73- bail!(74- "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \75- Alternatively, use the '--show-output' option to debug what went wrong.",76- result.status.code().map_or(77- "The process has been terminated by a signal".into(),78- |c| format!("Command terminated with non-zero exit code: {}", c)79- )80- );81- }82-83- // Correct for shell spawning time84- if let Some(spawning_time) = shell_spawning_time {85- time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);86- time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);87- time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);88- }89-90- Ok((91- TimingResult {92- time_real,93- time_user,94- time_system,95- },96- result.status,97- ))98-}99-100-/// Measure the average shell spawning time101-pub fn mean_shell_spawning_time(102- shell: &Shell,103- style: OutputStyleOption,104- command_output_policy: CommandOutputPolicy,105-) -> Result<TimingResult> {106- const COUNT: u64 = 50;107- let progress_bar = if style != OutputStyleOption::Disabled {108- Some(get_progress_bar(109- COUNT,110- "Measuring shell spawning time",111- style,112- ))113- } else {114- None115- };116-117- let mut times_real: Vec<Second> = vec![];118- let mut times_user: Vec<Second> = vec![];119- let mut times_system: Vec<Second> = vec![];120-121- for _ in 0..COUNT {122- // Just run the shell without any command123- let res = time_shell_command(124- shell,125- &Command::new(None, ""),126- command_output_policy,127- CmdFailureAction::RaiseError,128- None,129- );130-131- match res {132- Err(_) => {133- let shell_cmd = if cfg!(windows) {134- format!("{} /C \"\"", shell)135- } else {136- format!("{} -c \"\"", shell)137- };138-139- bail!(140- "Could not measure shell execution time. Make sure you can run '{}'.",141- shell_cmd142- );143- }144- Ok((r, _)) => {145- times_real.push(r.time_real);146- times_user.push(r.time_user);147- times_system.push(r.time_system);148- }149- }150-151- if let Some(bar) = progress_bar.as_ref() {152- bar.inc(1)153- }154- }155-156- if let Some(bar) = progress_bar.as_ref() {157- bar.finish_and_clear()158- }159-160- Ok(TimingResult {161- time_real: mean(×_real),162- time_user: mean(×_user),163- time_system: mean(×_system),164- })165-}166-167-fn run_intermediate_command(168- shell: &Shell,169- command: &Option<Command<'_>>,170- command_output_policy: CommandOutputPolicy,171- error_output: &'static str,172-) -> Result<TimingResult> {173- if let Some(ref cmd) = command {174- let res = time_shell_command(175- shell,176- cmd,177- command_output_policy,178- CmdFailureAction::RaiseError,179- None,180- );181- if res.is_err() {182- bail!(error_output);183- }184- return res.map(|r| r.0);185- }186- Ok(TimingResult {187- ..Default::default()188- })189-}190-191-/// Run the command specified by `--setup`.192-fn run_setup_command(193- shell: &Shell,194- command: &Option<Command<'_>>,195- output_policy: CommandOutputPolicy,196-) -> Result<TimingResult> {197- let error_output = "The setup command terminated with a non-zero exit code. \198- Append ' || true' to the command if you are sure that this can be ignored.";199-200- run_intermediate_command(shell, command, output_policy, error_output)201-}202-203-/// Run the command specified by `--prepare`.204-fn run_preparation_command(205- shell: &Shell,206- command: &Option<Command<'_>>,207- output_policy: CommandOutputPolicy,208-) -> Result<TimingResult> {209- let error_output = "The preparation command terminated with a non-zero exit code. \210- Append ' || true' to the command if you are sure that this can be ignored.";211-212- run_intermediate_command(shell, command, output_policy, error_output)213-}214-215-/// Run the command specified by `--cleanup`.216-fn run_cleanup_command(217- shell: &Shell,218- command: &Option<Command<'_>>,219- output_policy: CommandOutputPolicy,220-) -> Result<TimingResult> {221- let error_output = "The cleanup command terminated with a non-zero exit code. \222- Append ' || true' to the command if you are sure that this can be ignored.";223-224- run_intermediate_command(shell, command, output_policy, error_output)225-}226-227-/// Run the benchmark for a single shell command228-pub fn run_benchmark(229- num: usize,230- cmd: &Command<'_>,231- shell_spawning_time: TimingResult,232- options: &Options,233-) -> Result<BenchmarkResult> {234- let command_name = cmd.get_name();235- if options.output_style != OutputStyleOption::Disabled {236- println!(237- "{}{}: {}",238- "Benchmark ".bold(),239- (num + 1).to_string().bold(),240- command_name,241- );242- }243-244- let mut times_real: Vec<Second> = vec![];245- let mut times_user: Vec<Second> = vec![];246- let mut times_system: Vec<Second> = vec![];247- let mut exit_codes: Vec<Option<i32>> = vec![];248- let mut all_succeeded = true;249-250- // Run init command251- let prepare_cmd = options.preparation_command.as_ref().map(|values| {252- let preparation_command = if values.len() == 1 {253- &values[0]254- } else {255- &values[num]256- };257- Command::new_parametrized(None, preparation_command, cmd.get_parameters().clone())258- });259-260- // Run setup command261- let setup_cmd = options.setup_command.as_ref().map(|setup_command| {262- Command::new_parametrized(None, setup_command, cmd.get_parameters().clone())263- });264- run_setup_command(&options.shell, &setup_cmd, options.command_output_policy)?;265-266- // Warmup phase267- if options.warmup_count > 0 {268- let progress_bar = if options.output_style != OutputStyleOption::Disabled {269- Some(get_progress_bar(270- options.warmup_count,271- "Performing warmup runs",272- options.output_style,273- ))274- } else {275- None276- };277-278- for _ in 0..options.warmup_count {279- let _ = run_preparation_command(280- &options.shell,281- &prepare_cmd,282- options.command_output_policy,283- )?;284- let _ = time_shell_command(285- &options.shell,286- cmd,287- options.command_output_policy,288- options.command_failure_action,289- None,290- )?;291- if let Some(bar) = progress_bar.as_ref() {292- bar.inc(1)293- }294- }295- if let Some(bar) = progress_bar.as_ref() {296- bar.finish_and_clear()297- }298- }299-300- // Set up progress bar (and spinner for initial measurement)301- let progress_bar = if options.output_style != OutputStyleOption::Disabled {302- Some(get_progress_bar(303- options.run_bounds.min,304- "Initial time measurement",305- options.output_style,306- ))307- } else {308- None309- };310-311- let prepare_result =312- run_preparation_command(&options.shell, &prepare_cmd, options.command_output_policy)?;313-314- // Initial timing run315- let (res, status) = time_shell_command(316- &options.shell,317- cmd,318- options.command_output_policy,319- options.command_failure_action,320- Some(shell_spawning_time),321- )?;322- let success = status.success();323-324- // Determine number of benchmark runs325- let runs_in_min_time = (options.min_benchmarking_time326- / (res.time_real + prepare_result.time_real + shell_spawning_time.time_real))327- as u64;328-329- let count = {330- let min = cmp::max(runs_in_min_time, options.run_bounds.min);331-332- options333- .run_bounds334- .max335- .as_ref()336- .map(|max| cmp::min(min, *max))337- .unwrap_or(min)338- };339-340- let count_remaining = count - 1;341-342- // Save the first result343- times_real.push(res.time_real);344- times_user.push(res.time_user);345- times_system.push(res.time_system);346- exit_codes.push(extract_exit_code(status));347-348- all_succeeded = all_succeeded && success;349-350- // Re-configure the progress bar351- if let Some(bar) = progress_bar.as_ref() {352- bar.set_length(count)353- }354- if let Some(bar) = progress_bar.as_ref() {355- bar.inc(1)356- }357-358- // Gather statistics359- for _ in 0..count_remaining {360- run_preparation_command(&options.shell, &prepare_cmd, options.command_output_policy)?;361-362- let msg = {363- let mean = format_duration(mean(×_real), options.time_unit);364- format!("Current estimate: {}", mean.to_string().green())365- };366-367- if let Some(bar) = progress_bar.as_ref() {368- bar.set_message(msg.to_owned())369- }370-371- let (res, status) = time_shell_command(372- &options.shell,373- cmd,374- options.command_output_policy,375- options.command_failure_action,376- Some(shell_spawning_time),377- )?;378- let success = status.success();379-380- times_real.push(res.time_real);381- times_user.push(res.time_user);382- times_system.push(res.time_system);383- exit_codes.push(extract_exit_code(status));384-385- all_succeeded = all_succeeded && success;386-387- if let Some(bar) = progress_bar.as_ref() {388- bar.inc(1)389- }390- }391-392- if let Some(bar) = progress_bar.as_ref() {393- bar.finish_and_clear()394- }395-396- // Compute statistical quantities397- let t_num = times_real.len();398- let t_mean = mean(×_real);399- let t_stddev = if times_real.len() > 1 {400- Some(standard_deviation(×_real, Some(t_mean)))401- } else {402- None403- };404- let t_median = median(×_real);405- let t_min = min(×_real);406- let t_max = max(×_real);407-408- let user_mean = mean(×_user);409- let system_mean = mean(×_system);410-411- // Formatting and console output412- let (mean_str, time_unit) = format_duration_unit(t_mean, options.time_unit);413- let min_str = format_duration(t_min, Some(time_unit));414- let max_str = format_duration(t_max, Some(time_unit));415- let num_str = format!("{} runs", t_num);416-417- let user_str = format_duration(user_mean, Some(time_unit));418- let system_str = format_duration(system_mean, Some(time_unit));419-420- if options.output_style != OutputStyleOption::Disabled {421- if times_real.len() == 1 {422- println!(423- " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",424- "abs".green().bold(),425- mean_str.green().bold(),426- " ".to_string(), // alignment427- user_str.blue(),428- system_str.blue()429- );430- } else {431- let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));432-433- println!(434- " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",435- "mean".green().bold(),436- "σ".green(),437- mean_str.green().bold(),438- stddev_str.green(),439- user_str.blue(),440- system_str.blue()441- );442-443- println!(444- " Range ({} … {}): {:>8} … {:>8} {}",445- "min".cyan(),446- "max".purple(),447- min_str.cyan(),448- max_str.purple(),449- num_str.dimmed()450- );451- }452- }453-454- // Warnings455- let mut warnings = vec![];456-457- // Check execution time458- if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {459- warnings.push(Warnings::FastExecutionTime);460- }461-462- // Check programm exit codes463- if !all_succeeded {464- warnings.push(Warnings::NonZeroExitCode);465- }466-467- // Run outlier detection468- let scores = modified_zscores(×_real);469- if scores[0] > OUTLIER_THRESHOLD {470- warnings.push(Warnings::SlowInitialRun(times_real[0]));471- } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {472- warnings.push(Warnings::OutliersDetected);473- }474-475- if !warnings.is_empty() {476- eprintln!(" ");477-478- for warning in &warnings {479- eprintln!(" {}: {}", "Warning".yellow(), warning);480- }481- }482-483- if options.output_style != OutputStyleOption::Disabled {484- println!(" ");485- }486-487- // Run cleanup command488- let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {489- Command::new_parametrized(None, cleanup_command, cmd.get_parameters().clone())490- });491- run_cleanup_command(&options.shell, &cleanup_cmd, options.command_output_policy)?;492-493- Ok(BenchmarkResult {494- command: command_name,495- mean: t_mean,496- stddev: t_stddev,497- median: t_median,498- user: user_mean,499- system: system_mean,500- min: t_min,501- max: t_max,502- times: Some(times_real),503- exit_codes,504- parameters: cmd505- .get_parameters()506- .iter()507- .map(|(name, value)| ((*name).to_string(), value.to_string()))508- .collect(),509- })510-}modified:src/benchmark/relative_speed.rs+1 added-1 removed
1 use std::cmp::Ordering;2 3-use super::result::BenchmarkResult;3+use super::benchmark_result::BenchmarkResult;4 use crate::util::units::Scalar;5 6 #[derive(Debug)]7 pub struct BenchmarkResultWithRelativeSpeed<'a> {93 unmodified linesdeleted:src/benchmark/result.rs-46 removed
1-use std::collections::BTreeMap;2-3-use serde::Serialize;4-5-use crate::util::units::Second;6-7-/// Set of values that will be exported.8-// NOTE: `serde` is used for JSON serialization, but not for CSV serialization due to the9-// `parameters` map. Update `src/hyperfine/export/csv.rs` with new fields, as appropriate.10-#[derive(Debug, Default, Clone, Serialize, PartialEq)]11-pub struct BenchmarkResult {12- /// The command that was run13- pub command: String,14-15- /// The mean run time16- pub mean: Second,17-18- /// The standard deviation of all run times. Not available if only one run has been performed19- pub stddev: Option<Second>,20-21- /// The median run time22- pub median: Second,23-24- /// Time spend in user space25- pub user: Second,26-27- /// Time spent in system space28- pub system: Second,29-30- /// Min time measured31- pub min: Second,32-33- /// Max time measured34- pub max: Second,35-36- /// All run time measurements37- #[serde(skip_serializing_if = "Option::is_none")]38- pub times: Option<Vec<Second>>,39-40- /// All run exit codes41- pub exit_codes: Vec<Option<i32>>,42-43- /// Any parameter values used44- #[serde(skip_serializing_if = "BTreeMap::is_empty")]45- pub parameters: BTreeMap<String, String>,46-}modified:src/benchmark/scheduler.rs+492 added-5 removed
1+use std::cmp;2+use std::process::{ExitStatus, Stdio};3+4+use colored::*;5+use statistical::{mean, median, standard_deviation};6+7+use super::benchmark_result::BenchmarkResult;8+use super::timing_result::TimingResult;9+use super::{relative_speed, MIN_EXECUTION_TIME};10+11+use crate::command::Command;12 use crate::command::Commands;13 use crate::export::ExportManager;3-use crate::options::{Options, OutputStyleOption};14+use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};15+use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};16+use crate::output::format::{format_duration, format_duration_unit};17+use crate::output::progress_bar::get_progress_bar;18+use crate::output::warnings::Warnings;19+use crate::shell::execute_and_time;20+use crate::timer::wallclocktimer::WallClockTimer;21+use crate::timer::{TimerStart, TimerStop};22+use crate::util::exit_code::extract_exit_code;23+use crate::util::min_max::{max, min};24+use crate::util::units::Second;25 5-use super::{mean_shell_spawning_time, relative_speed, result::BenchmarkResult, run_benchmark};26+use anyhow::{bail, Result};27 7-use anyhow::Result;8-use colored::*;9-28 pub struct Scheduler<'a> {29 commands: &'a Commands<'a>,30 options: &'a Options,31 export_manager: &'a ExportManager,75 unmodified lines107 );108 }109 }110 }111+112+/// Correct for shell spawning time113+fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {114+ if time < shell_spawning_time {115+ 0.0116+ } else {117+ time - shell_spawning_time118+ }119+}120+121+/// Run the given shell command and measure the execution time122+pub fn time_shell_command(123+ shell: &Shell,124+ command: &Command<'_>,125+ command_output_policy: CommandOutputPolicy,126+ failure_action: CmdFailureAction,127+ shell_spawning_time: Option<TimingResult>,128+) -> Result<(TimingResult, ExitStatus)> {129+ let (stdout, stderr) = match command_output_policy {130+ CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),131+ CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),132+ };133+134+ let wallclock_timer = WallClockTimer::start();135+ let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;136+ let mut time_real = wallclock_timer.stop();137+138+ let mut time_user = result.user_time;139+ let mut time_system = result.system_time;140+141+ if failure_action == CmdFailureAction::RaiseError && !result.status.success() {142+ bail!(143+ "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \144+ Alternatively, use the '--show-output' option to debug what went wrong.",145+ result.status.code().map_or(146+ "The process has been terminated by a signal".into(),147+ |c| format!("Command terminated with non-zero exit code: {}", c)148+ )149+ );150+ }151+152+ // Correct for shell spawning time153+ if let Some(spawning_time) = shell_spawning_time {154+ time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);155+ time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);156+ time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);157+ }158+159+ Ok((160+ TimingResult {161+ time_real,162+ time_user,163+ time_system,164+ },165+ result.status,166+ ))167+}168+169+/// Measure the average shell spawning time170+pub fn mean_shell_spawning_time(171+ shell: &Shell,172+ style: OutputStyleOption,173+ command_output_policy: CommandOutputPolicy,174+) -> Result<TimingResult> {175+ const COUNT: u64 = 50;176+ let progress_bar = if style != OutputStyleOption::Disabled {177+ Some(get_progress_bar(178+ COUNT,179+ "Measuring shell spawning time",180+ style,181+ ))182+ } else {183+ None184+ };185+186+ let mut times_real: Vec<Second> = vec![];187+ let mut times_user: Vec<Second> = vec![];188+ let mut times_system: Vec<Second> = vec![];189+190+ for _ in 0..COUNT {191+ // Just run the shell without any command192+ let res = time_shell_command(193+ shell,194+ &Command::new(None, ""),195+ command_output_policy,196+ CmdFailureAction::RaiseError,197+ None,198+ );199+200+ match res {201+ Err(_) => {202+ let shell_cmd = if cfg!(windows) {203+ format!("{} /C \"\"", shell)204+ } else {205+ format!("{} -c \"\"", shell)206+ };207+208+ bail!(209+ "Could not measure shell execution time. Make sure you can run '{}'.",210+ shell_cmd211+ );212+ }213+ Ok((r, _)) => {214+ times_real.push(r.time_real);215+ times_user.push(r.time_user);216+ times_system.push(r.time_system);217+ }218+ }219+220+ if let Some(bar) = progress_bar.as_ref() {221+ bar.inc(1)222+ }223+ }224+225+ if let Some(bar) = progress_bar.as_ref() {226+ bar.finish_and_clear()227+ }228+229+ Ok(TimingResult {230+ time_real: mean(×_real),231+ time_user: mean(×_user),232+ time_system: mean(×_system),233+ })234+}235+236+fn run_intermediate_command(237+ shell: &Shell,238+ command: &Option<Command<'_>>,239+ command_output_policy: CommandOutputPolicy,240+ error_output: &'static str,241+) -> Result<TimingResult> {242+ if let Some(ref cmd) = command {243+ let res = time_shell_command(244+ shell,245+ cmd,246+ command_output_policy,247+ CmdFailureAction::RaiseError,248+ None,249+ );250+ if res.is_err() {251+ bail!(error_output);252+ }253+ return res.map(|r| r.0);254+ }255+ Ok(TimingResult {256+ ..Default::default()257+ })258+}259+260+/// Run the command specified by `--setup`.261+fn run_setup_command(262+ shell: &Shell,263+ command: &Option<Command<'_>>,264+ output_policy: CommandOutputPolicy,265+) -> Result<TimingResult> {266+ let error_output = "The setup command terminated with a non-zero exit code. \267+ Append ' || true' to the command if you are sure that this can be ignored.";268+269+ run_intermediate_command(shell, command, output_policy, error_output)270+}271+272+/// Run the command specified by `--prepare`.273+fn run_preparation_command(274+ shell: &Shell,275+ command: &Option<Command<'_>>,276+ output_policy: CommandOutputPolicy,277+) -> Result<TimingResult> {278+ let error_output = "The preparation command terminated with a non-zero exit code. \279+ Append ' || true' to the command if you are sure that this can be ignored.";280+281+ run_intermediate_command(shell, command, output_policy, error_output)282+}283+284+/// Run the command specified by `--cleanup`.285+fn run_cleanup_command(286+ shell: &Shell,287+ command: &Option<Command<'_>>,288+ output_policy: CommandOutputPolicy,289+) -> Result<TimingResult> {290+ let error_output = "The cleanup command terminated with a non-zero exit code. \291+ Append ' || true' to the command if you are sure that this can be ignored.";292+293+ run_intermediate_command(shell, command, output_policy, error_output)294+}295+296+/// Run the benchmark for a single shell command297+pub fn run_benchmark(298+ num: usize,299+ cmd: &Command<'_>,300+ shell_spawning_time: TimingResult,301+ options: &Options,302+) -> Result<BenchmarkResult> {303+ let command_name = cmd.get_name();304+ if options.output_style != OutputStyleOption::Disabled {305+ println!(306+ "{}{}: {}",307+ "Benchmark ".bold(),308+ (num + 1).to_string().bold(),309+ command_name,310+ );311+ }312+313+ let mut times_real: Vec<Second> = vec![];314+ let mut times_user: Vec<Second> = vec![];315+ let mut times_system: Vec<Second> = vec![];316+ let mut exit_codes: Vec<Option<i32>> = vec![];317+ let mut all_succeeded = true;318+319+ // Run init command320+ let prepare_cmd = options.preparation_command.as_ref().map(|values| {321+ let preparation_command = if values.len() == 1 {322+ &values[0]323+ } else {324+ &values[num]325+ };326+ Command::new_parametrized(None, preparation_command, cmd.get_parameters().clone())327+ });328+329+ // Run setup command330+ let setup_cmd = options.setup_command.as_ref().map(|setup_command| {331+ Command::new_parametrized(None, setup_command, cmd.get_parameters().clone())332+ });333+ run_setup_command(&options.shell, &setup_cmd, options.command_output_policy)?;334+335+ // Warmup phase336+ if options.warmup_count > 0 {337+ let progress_bar = if options.output_style != OutputStyleOption::Disabled {338+ Some(get_progress_bar(339+ options.warmup_count,340+ "Performing warmup runs",341+ options.output_style,342+ ))343+ } else {344+ None345+ };346+347+ for _ in 0..options.warmup_count {348+ let _ = run_preparation_command(349+ &options.shell,350+ &prepare_cmd,351+ options.command_output_policy,352+ )?;353+ let _ = time_shell_command(354+ &options.shell,355+ cmd,356+ options.command_output_policy,357+ options.command_failure_action,358+ None,359+ )?;360+ if let Some(bar) = progress_bar.as_ref() {361+ bar.inc(1)362+ }363+ }364+ if let Some(bar) = progress_bar.as_ref() {365+ bar.finish_and_clear()366+ }367+ }368+369+ // Set up progress bar (and spinner for initial measurement)370+ let progress_bar = if options.output_style != OutputStyleOption::Disabled {371+ Some(get_progress_bar(372+ options.run_bounds.min,373+ "Initial time measurement",374+ options.output_style,375+ ))376+ } else {377+ None378+ };379+380+ let prepare_result =381+ run_preparation_command(&options.shell, &prepare_cmd, options.command_output_policy)?;382+383+ // Initial timing run384+ let (res, status) = time_shell_command(385+ &options.shell,386+ cmd,387+ options.command_output_policy,388+ options.command_failure_action,389+ Some(shell_spawning_time),390+ )?;391+ let success = status.success();392+393+ // Determine number of benchmark runs394+ let runs_in_min_time = (options.min_benchmarking_time395+ / (res.time_real + prepare_result.time_real + shell_spawning_time.time_real))396+ as u64;397+398+ let count = {399+ let min = cmp::max(runs_in_min_time, options.run_bounds.min);400+401+ options402+ .run_bounds403+ .max404+ .as_ref()405+ .map(|max| cmp::min(min, *max))406+ .unwrap_or(min)407+ };408+409+ let count_remaining = count - 1;410+411+ // Save the first result412+ times_real.push(res.time_real);413+ times_user.push(res.time_user);414+ times_system.push(res.time_system);415+ exit_codes.push(extract_exit_code(status));416+417+ all_succeeded = all_succeeded && success;418+419+ // Re-configure the progress bar420+ if let Some(bar) = progress_bar.as_ref() {421+ bar.set_length(count)422+ }423+ if let Some(bar) = progress_bar.as_ref() {424+ bar.inc(1)425+ }426+427+ // Gather statistics428+ for _ in 0..count_remaining {429+ run_preparation_command(&options.shell, &prepare_cmd, options.command_output_policy)?;430+431+ let msg = {432+ let mean = format_duration(mean(×_real), options.time_unit);433+ format!("Current estimate: {}", mean.to_string().green())434+ };435+436+ if let Some(bar) = progress_bar.as_ref() {437+ bar.set_message(msg.to_owned())438+ }439+440+ let (res, status) = time_shell_command(441+ &options.shell,442+ cmd,443+ options.command_output_policy,444+ options.command_failure_action,445+ Some(shell_spawning_time),446+ )?;447+ let success = status.success();448+449+ times_real.push(res.time_real);450+ times_user.push(res.time_user);451+ times_system.push(res.time_system);452+ exit_codes.push(extract_exit_code(status));453+454+ all_succeeded = all_succeeded && success;455+456+ if let Some(bar) = progress_bar.as_ref() {457+ bar.inc(1)458+ }459+ }460+461+ if let Some(bar) = progress_bar.as_ref() {462+ bar.finish_and_clear()463+ }464+465+ // Compute statistical quantities466+ let t_num = times_real.len();467+ let t_mean = mean(×_real);468+ let t_stddev = if times_real.len() > 1 {469+ Some(standard_deviation(×_real, Some(t_mean)))470+ } else {471+ None472+ };473+ let t_median = median(×_real);474+ let t_min = min(×_real);475+ let t_max = max(×_real);476+477+ let user_mean = mean(×_user);478+ let system_mean = mean(×_system);479+480+ // Formatting and console output481+ let (mean_str, time_unit) = format_duration_unit(t_mean, options.time_unit);482+ let min_str = format_duration(t_min, Some(time_unit));483+ let max_str = format_duration(t_max, Some(time_unit));484+ let num_str = format!("{} runs", t_num);485+486+ let user_str = format_duration(user_mean, Some(time_unit));487+ let system_str = format_duration(system_mean, Some(time_unit));488+489+ if options.output_style != OutputStyleOption::Disabled {490+ if times_real.len() == 1 {491+ println!(492+ " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",493+ "abs".green().bold(),494+ mean_str.green().bold(),495+ " ".to_string(), // alignment496+ user_str.blue(),497+ system_str.blue()498+ );499+ } else {500+ let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));501+502+ println!(503+ " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",504+ "mean".green().bold(),505+ "σ".green(),506+ mean_str.green().bold(),507+ stddev_str.green(),508+ user_str.blue(),509+ system_str.blue()510+ );511+512+ println!(513+ " Range ({} … {}): {:>8} … {:>8} {}",514+ "min".cyan(),515+ "max".purple(),516+ min_str.cyan(),517+ max_str.purple(),518+ num_str.dimmed()519+ );520+ }521+ }522+523+ // Warnings524+ let mut warnings = vec![];525+526+ // Check execution time527+ if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {528+ warnings.push(Warnings::FastExecutionTime);529+ }530+531+ // Check programm exit codes532+ if !all_succeeded {533+ warnings.push(Warnings::NonZeroExitCode);534+ }535+536+ // Run outlier detection537+ let scores = modified_zscores(×_real);538+ if scores[0] > OUTLIER_THRESHOLD {539+ warnings.push(Warnings::SlowInitialRun(times_real[0]));540+ } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {541+ warnings.push(Warnings::OutliersDetected);542+ }543+544+ if !warnings.is_empty() {545+ eprintln!(" ");546+547+ for warning in &warnings {548+ eprintln!(" {}: {}", "Warning".yellow(), warning);549+ }550+ }551+552+ if options.output_style != OutputStyleOption::Disabled {553+ println!(" ");554+ }555+556+ // Run cleanup command557+ let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {558+ Command::new_parametrized(None, cleanup_command, cmd.get_parameters().clone())559+ });560+ run_cleanup_command(&options.shell, &cleanup_cmd, options.command_output_policy)?;561+562+ Ok(BenchmarkResult {563+ command: command_name,564+ mean: t_mean,565+ stddev: t_stddev,566+ median: t_median,567+ user: user_mean,568+ system: system_mean,569+ min: t_min,570+ max: t_max,571+ times: Some(times_real),572+ exit_codes,573+ parameters: cmd574+ .get_parameters()575+ .iter()576+ .map(|(name, value)| ((*name).to_string(), value.to_string()))577+ .collect(),578+ })579+}added:src/benchmark/timing_result.rs+14 added
1+use crate::util::units::Second;2+3+/// Results from timing a single command4+#[derive(Debug, Default, Copy, Clone)]5+pub struct TimingResult {6+ /// Wall clock time7+ pub time_real: Second,8+9+ /// Time spent in user mode10+ pub time_user: Second,11+12+ /// Time spent in kernel mode13+ pub time_system: Second,14+}modified:src/export/asciidoc.rs+1 added-1 removed
1+use crate::benchmark::benchmark_result::BenchmarkResult;2 use crate::benchmark::relative_speed::{self, BenchmarkResultWithRelativeSpeed};2-use crate::benchmark::result::BenchmarkResult;3 use crate::output::format::format_duration_value;4 use crate::util::units::Unit;5 6 use super::Exporter;267 unmodified linesmodified:src/export/csv.rs+1 added-1 removed
1 unmodified line2 3 use csv::WriterBuilder;4 5 use super::Exporter;6-use crate::benchmark::result::BenchmarkResult;6+use crate::benchmark::benchmark_result::BenchmarkResult;7 use crate::util::units::Unit;8 9 use anyhow::Result;10 100 unmodified linesmodified:src/export/json.rs+1 added-1 removed
1 use serde::*;2 use serde_json::to_vec_pretty;3 4 use super::Exporter;5-use crate::benchmark::result::BenchmarkResult;5+use crate::benchmark::benchmark_result::BenchmarkResult;6 use crate::util::units::Unit;7 8 use anyhow::Result;9 18 unmodified linesmodified:src/export/markdown.rs+1 added-1 removed
1 use super::Exporter;2+use crate::benchmark::benchmark_result::BenchmarkResult;3 use crate::benchmark::relative_speed::{self, BenchmarkResultWithRelativeSpeed};3-use crate::benchmark::result::BenchmarkResult;4 use crate::output::format::format_duration_value;5 use crate::util::units::Unit;6 7 use anyhow::{anyhow, Result};286 unmodified linesmodified:src/export/mod.rs+1 added-1 removed
9 unmodified lines10 use self::csv::CsvExporter;11 use self::json::JsonExporter;12 use self::markdown::MarkdownExporter;13 14-use crate::benchmark::result::BenchmarkResult;14+use crate::benchmark::benchmark_result::BenchmarkResult;15 use crate::util::units::Unit;16 17 use anyhow::{Context, Result};18 use clap::ArgMatches;89 unmodified lines