New 'benchmark' module folder
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 cd38e9c · Browse files · 11 files·+572 added−570 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+572 added−570 removed
- other:+572 added−570 removed
Provenance
- Commit
e5e4c8c- Tree
39e61b8- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
cd38e9c
11 files changed+572 added−570 removed
added:src/benchmark/mod.rs+518 added
1+pub mod result;2+3+use std::cmp;4+use std::process::{ExitStatus, Stdio};5+6+use colored::*;7+use statistical::{mean, median, standard_deviation};8+9+use crate::benchmark::result::BenchmarkResult;10+use crate::command::Command;11+use crate::format::{format_duration, format_duration_unit};12+use crate::min_max::{max, min};13+use crate::options::{CmdFailureAction, Options, OutputStyleOption, Shell};14+use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};15+use crate::progress_bar::get_progress_bar;16+use crate::shell::execute_and_time;17+use crate::timer::wallclocktimer::WallClockTimer;18+use crate::timer::{TimerStart, TimerStop};19+use crate::units::Second;20+use crate::warnings::Warnings;21+22+use anyhow::{bail, Result};23+24+/// Threshold for warning about fast execution time25+pub const MIN_EXECUTION_TIME: Second = 5e-3;26+27+/// Results from timing a single shell command28+#[derive(Debug, Default, Copy, Clone)]29+pub struct TimingResult {30+ /// Wall clock time31+ pub time_real: Second,32+33+ /// Time spent in user mode34+ pub time_user: Second,35+36+ /// Time spent in kernel mode37+ pub time_system: Second,38+}39+40+/// Correct for shell spawning time41+fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {42+ if time < shell_spawning_time {43+ 0.044+ } else {45+ time - shell_spawning_time46+ }47+}48+49+/// Run the given shell command and measure the execution time50+pub fn time_shell_command(51+ shell: &Shell,52+ command: &Command<'_>,53+ show_output: bool,54+ failure_action: CmdFailureAction,55+ shell_spawning_time: Option<TimingResult>,56+) -> Result<(TimingResult, ExitStatus)> {57+ let (stdout, stderr) = if show_output {58+ (Stdio::inherit(), Stdio::inherit())59+ } else {60+ (Stdio::null(), Stdio::null())61+ };62+63+ let wallclock_timer = WallClockTimer::start();64+ let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;65+ let mut time_real = wallclock_timer.stop();66+67+ let mut time_user = result.user_time;68+ let mut time_system = result.system_time;69+70+ if failure_action == CmdFailureAction::RaiseError && !result.status.success() {71+ bail!(72+ "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \73+ Alternatively, use the '--show-output' option to debug what went wrong.",74+ result.status.code().map_or(75+ "The process has been terminated by a signal".into(),76+ |c| format!("Command terminated with non-zero exit code: {}", c)77+ )78+ );79+ }80+81+ // Correct for shell spawning time82+ if let Some(spawning_time) = shell_spawning_time {83+ time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);84+ time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);85+ time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);86+ }87+88+ Ok((89+ TimingResult {90+ time_real,91+ time_user,92+ time_system,93+ },94+ result.status,95+ ))96+}97+98+/// Measure the average shell spawning time99+pub fn mean_shell_spawning_time(100+ shell: &Shell,101+ style: OutputStyleOption,102+ show_output: bool,103+) -> Result<TimingResult> {104+ const COUNT: u64 = 50;105+ let progress_bar = if style != OutputStyleOption::Disabled {106+ Some(get_progress_bar(107+ COUNT,108+ "Measuring shell spawning time",109+ style,110+ ))111+ } else {112+ None113+ };114+115+ let mut times_real: Vec<Second> = vec![];116+ let mut times_user: Vec<Second> = vec![];117+ let mut times_system: Vec<Second> = vec![];118+119+ for _ in 0..COUNT {120+ // Just run the shell without any command121+ let res = time_shell_command(122+ shell,123+ &Command::new(None, ""),124+ show_output,125+ CmdFailureAction::RaiseError,126+ None,127+ );128+129+ match res {130+ Err(_) => {131+ let shell_cmd = if cfg!(windows) {132+ format!("{} /C \"\"", shell)133+ } else {134+ format!("{} -c \"\"", shell)135+ };136+137+ bail!(138+ "Could not measure shell execution time. Make sure you can run '{}'.",139+ shell_cmd140+ );141+ }142+ Ok((r, _)) => {143+ times_real.push(r.time_real);144+ times_user.push(r.time_user);145+ times_system.push(r.time_system);146+ }147+ }148+149+ if let Some(bar) = progress_bar.as_ref() {150+ bar.inc(1)151+ }152+ }153+154+ if let Some(bar) = progress_bar.as_ref() {155+ bar.finish_and_clear()156+ }157+158+ Ok(TimingResult {159+ time_real: mean(×_real),160+ time_user: mean(×_user),161+ time_system: mean(×_system),162+ })163+}164+165+fn run_intermediate_command(166+ shell: &Shell,167+ command: &Option<Command<'_>>,168+ show_output: bool,169+ error_output: &'static str,170+) -> Result<TimingResult> {171+ if let Some(ref cmd) = command {172+ let res = time_shell_command(shell, cmd, show_output, CmdFailureAction::RaiseError, None);173+ if res.is_err() {174+ bail!(error_output);175+ }176+ return res.map(|r| r.0);177+ }178+ Ok(TimingResult {179+ ..Default::default()180+ })181+}182+183+/// Run the command specified by `--setup`.184+fn run_setup_command(185+ shell: &Shell,186+ command: &Option<Command<'_>>,187+ show_output: bool,188+) -> Result<TimingResult> {189+ let error_output = "The setup command terminated with a non-zero exit code. \190+ Append ' || true' to the command if you are sure that this can be ignored.";191+192+ run_intermediate_command(shell, command, show_output, error_output)193+}194+195+/// Run the command specified by `--prepare`.196+fn run_preparation_command(197+ shell: &Shell,198+ command: &Option<Command<'_>>,199+ show_output: bool,200+) -> Result<TimingResult> {201+ let error_output = "The preparation command terminated with a non-zero exit code. \202+ Append ' || true' to the command if you are sure that this can be ignored.";203+204+ run_intermediate_command(shell, command, show_output, error_output)205+}206+207+/// Run the command specified by `--cleanup`.208+fn run_cleanup_command(209+ shell: &Shell,210+ command: &Option<Command<'_>>,211+ show_output: bool,212+) -> Result<TimingResult> {213+ let error_output = "The cleanup command terminated with a non-zero exit code. \214+ Append ' || true' to the command if you are sure that this can be ignored.";215+216+ run_intermediate_command(shell, command, show_output, error_output)217+}218+219+#[cfg(unix)]220+fn extract_exit_code(status: ExitStatus) -> Option<i32> {221+ use std::os::unix::process::ExitStatusExt;222+223+ /* From the ExitStatus::code documentation:224+ "On Unix, this will return None if the process was terminated by a signal."225+ In that case, ExitStatusExt::signal should never return None.226+ */227+ status.code().or_else(||228+ /* To differentiate between "normal" exit codes and signals, we are using229+ something similar to bash exit codes (https://tldp.org/LDP/abs/html/exitcodes.html)230+ by adding 128 to a signal integer value.231+ */232+ status.signal().map(|s| 128 + s))233+}234+235+#[cfg(not(unix))]236+fn extract_exit_code(status: ExitStatus) -> Option<i32> {237+ status.code()238+}239+240+/// Run the benchmark for a single shell command241+pub fn run_benchmark(242+ num: usize,243+ cmd: &Command<'_>,244+ shell_spawning_time: TimingResult,245+ options: &Options,246+) -> Result<BenchmarkResult> {247+ let command_name = cmd.get_name();248+ if options.output_style != OutputStyleOption::Disabled {249+ println!(250+ "{}{}: {}",251+ "Benchmark ".bold(),252+ (num + 1).to_string().bold(),253+ command_name,254+ );255+ }256+257+ let mut times_real: Vec<Second> = vec![];258+ let mut times_user: Vec<Second> = vec![];259+ let mut times_system: Vec<Second> = vec![];260+ let mut exit_codes: Vec<Option<i32>> = vec![];261+ let mut all_succeeded = true;262+263+ // Run init command264+ let prepare_cmd = options.preparation_command.as_ref().map(|values| {265+ let preparation_command = if values.len() == 1 {266+ &values[0]267+ } else {268+ &values[num]269+ };270+ Command::new_parametrized(None, preparation_command, cmd.get_parameters().clone())271+ });272+273+ // Run setup command274+ let setup_cmd = options.setup_command.as_ref().map(|setup_command| {275+ Command::new_parametrized(None, setup_command, cmd.get_parameters().clone())276+ });277+ run_setup_command(&options.shell, &setup_cmd, options.show_output)?;278+279+ // Warmup phase280+ if options.warmup_count > 0 {281+ let progress_bar = if options.output_style != OutputStyleOption::Disabled {282+ Some(get_progress_bar(283+ options.warmup_count,284+ "Performing warmup runs",285+ options.output_style,286+ ))287+ } else {288+ None289+ };290+291+ for _ in 0..options.warmup_count {292+ let _ = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;293+ let _ = time_shell_command(294+ &options.shell,295+ cmd,296+ options.show_output,297+ options.failure_action,298+ None,299+ )?;300+ if let Some(bar) = progress_bar.as_ref() {301+ bar.inc(1)302+ }303+ }304+ if let Some(bar) = progress_bar.as_ref() {305+ bar.finish_and_clear()306+ }307+ }308+309+ // Set up progress bar (and spinner for initial measurement)310+ let progress_bar = if options.output_style != OutputStyleOption::Disabled {311+ Some(get_progress_bar(312+ options.runs.min,313+ "Initial time measurement",314+ options.output_style,315+ ))316+ } else {317+ None318+ };319+320+ let prepare_res = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;321+322+ // Initial timing run323+ let (res, status) = time_shell_command(324+ &options.shell,325+ cmd,326+ options.show_output,327+ options.failure_action,328+ Some(shell_spawning_time),329+ )?;330+ let success = status.success();331+332+ // Determine number of benchmark runs333+ let runs_in_min_time = (options.min_time_sec334+ / (res.time_real + prepare_res.time_real + shell_spawning_time.time_real))335+ as u64;336+337+ let count = {338+ let min = cmp::max(runs_in_min_time, options.runs.min);339+340+ options341+ .runs342+ .max343+ .as_ref()344+ .map(|max| cmp::min(min, *max))345+ .unwrap_or(min)346+ };347+348+ let count_remaining = count - 1;349+350+ // Save the first result351+ times_real.push(res.time_real);352+ times_user.push(res.time_user);353+ times_system.push(res.time_system);354+ exit_codes.push(extract_exit_code(status));355+356+ all_succeeded = all_succeeded && success;357+358+ // Re-configure the progress bar359+ if let Some(bar) = progress_bar.as_ref() {360+ bar.set_length(count)361+ }362+ if let Some(bar) = progress_bar.as_ref() {363+ bar.inc(1)364+ }365+366+ // Gather statistics367+ for _ in 0..count_remaining {368+ run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;369+370+ let msg = {371+ let mean = format_duration(mean(×_real), options.time_unit);372+ format!("Current estimate: {}", mean.to_string().green())373+ };374+375+ if let Some(bar) = progress_bar.as_ref() {376+ bar.set_message(msg.to_owned())377+ }378+379+ let (res, status) = time_shell_command(380+ &options.shell,381+ cmd,382+ options.show_output,383+ options.failure_action,384+ Some(shell_spawning_time),385+ )?;386+ let success = status.success();387+388+ times_real.push(res.time_real);389+ times_user.push(res.time_user);390+ times_system.push(res.time_system);391+ exit_codes.push(extract_exit_code(status));392+393+ all_succeeded = all_succeeded && success;394+395+ if let Some(bar) = progress_bar.as_ref() {396+ bar.inc(1)397+ }398+ }399+400+ if let Some(bar) = progress_bar.as_ref() {401+ bar.finish_and_clear()402+ }403+404+ // Compute statistical quantities405+ let t_num = times_real.len();406+ let t_mean = mean(×_real);407+ let t_stddev = if times_real.len() > 1 {408+ Some(standard_deviation(×_real, Some(t_mean)))409+ } else {410+ None411+ };412+ let t_median = median(×_real);413+ let t_min = min(×_real);414+ let t_max = max(×_real);415+416+ let user_mean = mean(×_user);417+ let system_mean = mean(×_system);418+419+ // Formatting and console output420+ let (mean_str, time_unit) = format_duration_unit(t_mean, options.time_unit);421+ let min_str = format_duration(t_min, Some(time_unit));422+ let max_str = format_duration(t_max, Some(time_unit));423+ let num_str = format!("{} runs", t_num);424+425+ let user_str = format_duration(user_mean, Some(time_unit));426+ let system_str = format_duration(system_mean, Some(time_unit));427+428+ if options.output_style != OutputStyleOption::Disabled {429+ if times_real.len() == 1 {430+ println!(431+ " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",432+ "abs".green().bold(),433+ mean_str.green().bold(),434+ " ".to_string(), // alignment435+ user_str.blue(),436+ system_str.blue()437+ );438+ } else {439+ let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));440+441+ println!(442+ " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",443+ "mean".green().bold(),444+ "σ".green(),445+ mean_str.green().bold(),446+ stddev_str.green(),447+ user_str.blue(),448+ system_str.blue()449+ );450+451+ println!(452+ " Range ({} … {}): {:>8} … {:>8} {}",453+ "min".cyan(),454+ "max".purple(),455+ min_str.cyan(),456+ max_str.purple(),457+ num_str.dimmed()458+ );459+ }460+ }461+462+ // Warnings463+ let mut warnings = vec![];464+465+ // Check execution time466+ if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {467+ warnings.push(Warnings::FastExecutionTime);468+ }469+470+ // Check programm exit codes471+ if !all_succeeded {472+ warnings.push(Warnings::NonZeroExitCode);473+ }474+475+ // Run outlier detection476+ let scores = modified_zscores(×_real);477+ if scores[0] > OUTLIER_THRESHOLD {478+ warnings.push(Warnings::SlowInitialRun(times_real[0]));479+ } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {480+ warnings.push(Warnings::OutliersDetected);481+ }482+483+ if !warnings.is_empty() {484+ eprintln!(" ");485+486+ for warning in &warnings {487+ eprintln!(" {}: {}", "Warning".yellow(), warning);488+ }489+ }490+491+ if options.output_style != OutputStyleOption::Disabled {492+ println!(" ");493+ }494+495+ // Run cleanup command496+ let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {497+ Command::new_parametrized(None, cleanup_command, cmd.get_parameters().clone())498+ });499+ run_cleanup_command(&options.shell, &cleanup_cmd, options.show_output)?;500+501+ Ok(BenchmarkResult {502+ command: command_name,503+ mean: t_mean,504+ stddev: t_stddev,505+ median: t_median,506+ user: user_mean,507+ system: system_mean,508+ min: t_min,509+ max: t_max,510+ times: Some(times_real),511+ exit_codes,512+ parameters: cmd513+ .get_parameters()514+ .iter()515+ .map(|(name, value)| ((*name).to_string(), value.to_string()))516+ .collect(),517+ })518+}added:src/benchmark/result.rs+46 added
1+use std::collections::BTreeMap;2+3+use serde::Serialize;4+5+use crate::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/export/asciidoc.rs+1 added-1 removed
1-use crate::benchmark_result::BenchmarkResult;1+use crate::benchmark::result::BenchmarkResult;2 use crate::format::format_duration_value;3 use crate::relative_speed::{self, BenchmarkResultWithRelativeSpeed};4 use crate::units::Unit;5 268 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::result::BenchmarkResult;7 use crate::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::result::BenchmarkResult;6 use crate::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_result::BenchmarkResult;2+use crate::benchmark::result::BenchmarkResult;3 use crate::format::format_duration_value;4 use crate::relative_speed::{self, BenchmarkResultWithRelativeSpeed};5 use crate::units::Unit;6 287 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::result::BenchmarkResult;15 use crate::units::Unit;16 17 use anyhow::{Context, Result};18 use clap::ArgMatches;89 unmodified linesdeleted:src/benchmark_result.rs-46 removed
1-use std::collections::BTreeMap;2-3-use serde::Serialize;4-5-use crate::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-}deleted:src/benchmark.rs-516 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 crate::benchmark_result::BenchmarkResult;8-use crate::command::Command;9-use crate::format::{format_duration, format_duration_unit};10-use crate::min_max::{max, min};11-use crate::options::{CmdFailureAction, Options, OutputStyleOption, Shell};12-use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};13-use crate::progress_bar::get_progress_bar;14-use crate::shell::execute_and_time;15-use crate::timer::wallclocktimer::WallClockTimer;16-use crate::timer::{TimerStart, TimerStop};17-use crate::units::Second;18-use crate::warnings::Warnings;19-20-use anyhow::{bail, Result};21-22-/// Threshold for warning about fast execution time23-pub const MIN_EXECUTION_TIME: Second = 5e-3;24-25-/// Results from timing a single shell command26-#[derive(Debug, Default, Copy, Clone)]27-pub struct TimingResult {28- /// Wall clock time29- pub time_real: Second,30-31- /// Time spent in user mode32- pub time_user: Second,33-34- /// Time spent in kernel mode35- pub time_system: Second,36-}37-38-/// Correct for shell spawning time39-fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {40- if time < shell_spawning_time {41- 0.042- } else {43- time - shell_spawning_time44- }45-}46-47-/// Run the given shell command and measure the execution time48-pub fn time_shell_command(49- shell: &Shell,50- command: &Command<'_>,51- show_output: bool,52- failure_action: CmdFailureAction,53- shell_spawning_time: Option<TimingResult>,54-) -> Result<(TimingResult, ExitStatus)> {55- let (stdout, stderr) = if show_output {56- (Stdio::inherit(), Stdio::inherit())57- } else {58- (Stdio::null(), Stdio::null())59- };60-61- let wallclock_timer = WallClockTimer::start();62- let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;63- let mut time_real = wallclock_timer.stop();64-65- let mut time_user = result.user_time;66- let mut time_system = result.system_time;67-68- if failure_action == CmdFailureAction::RaiseError && !result.status.success() {69- bail!(70- "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \71- Alternatively, use the '--show-output' option to debug what went wrong.",72- result.status.code().map_or(73- "The process has been terminated by a signal".into(),74- |c| format!("Command terminated with non-zero exit code: {}", c)75- )76- );77- }78-79- // Correct for shell spawning time80- if let Some(spawning_time) = shell_spawning_time {81- time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);82- time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);83- time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);84- }85-86- Ok((87- TimingResult {88- time_real,89- time_user,90- time_system,91- },92- result.status,93- ))94-}95-96-/// Measure the average shell spawning time97-pub fn mean_shell_spawning_time(98- shell: &Shell,99- style: OutputStyleOption,100- show_output: bool,101-) -> Result<TimingResult> {102- const COUNT: u64 = 50;103- let progress_bar = if style != OutputStyleOption::Disabled {104- Some(get_progress_bar(105- COUNT,106- "Measuring shell spawning time",107- style,108- ))109- } else {110- None111- };112-113- let mut times_real: Vec<Second> = vec![];114- let mut times_user: Vec<Second> = vec![];115- let mut times_system: Vec<Second> = vec![];116-117- for _ in 0..COUNT {118- // Just run the shell without any command119- let res = time_shell_command(120- shell,121- &Command::new(None, ""),122- show_output,123- CmdFailureAction::RaiseError,124- None,125- );126-127- match res {128- Err(_) => {129- let shell_cmd = if cfg!(windows) {130- format!("{} /C \"\"", shell)131- } else {132- format!("{} -c \"\"", shell)133- };134-135- bail!(136- "Could not measure shell execution time. Make sure you can run '{}'.",137- shell_cmd138- );139- }140- Ok((r, _)) => {141- times_real.push(r.time_real);142- times_user.push(r.time_user);143- times_system.push(r.time_system);144- }145- }146-147- if let Some(bar) = progress_bar.as_ref() {148- bar.inc(1)149- }150- }151-152- if let Some(bar) = progress_bar.as_ref() {153- bar.finish_and_clear()154- }155-156- Ok(TimingResult {157- time_real: mean(×_real),158- time_user: mean(×_user),159- time_system: mean(×_system),160- })161-}162-163-fn run_intermediate_command(164- shell: &Shell,165- command: &Option<Command<'_>>,166- show_output: bool,167- error_output: &'static str,168-) -> Result<TimingResult> {169- if let Some(ref cmd) = command {170- let res = time_shell_command(shell, cmd, show_output, CmdFailureAction::RaiseError, None);171- if res.is_err() {172- bail!(error_output);173- }174- return res.map(|r| r.0);175- }176- Ok(TimingResult {177- ..Default::default()178- })179-}180-181-/// Run the command specified by `--setup`.182-fn run_setup_command(183- shell: &Shell,184- command: &Option<Command<'_>>,185- show_output: bool,186-) -> Result<TimingResult> {187- let error_output = "The setup command terminated with a non-zero exit code. \188- Append ' || true' to the command if you are sure that this can be ignored.";189-190- run_intermediate_command(shell, command, show_output, error_output)191-}192-193-/// Run the command specified by `--prepare`.194-fn run_preparation_command(195- shell: &Shell,196- command: &Option<Command<'_>>,197- show_output: bool,198-) -> Result<TimingResult> {199- let error_output = "The preparation command terminated with a non-zero exit code. \200- Append ' || true' to the command if you are sure that this can be ignored.";201-202- run_intermediate_command(shell, command, show_output, error_output)203-}204-205-/// Run the command specified by `--cleanup`.206-fn run_cleanup_command(207- shell: &Shell,208- command: &Option<Command<'_>>,209- show_output: bool,210-) -> Result<TimingResult> {211- let error_output = "The cleanup command terminated with a non-zero exit code. \212- Append ' || true' to the command if you are sure that this can be ignored.";213-214- run_intermediate_command(shell, command, show_output, error_output)215-}216-217-#[cfg(unix)]218-fn extract_exit_code(status: ExitStatus) -> Option<i32> {219- use std::os::unix::process::ExitStatusExt;220-221- /* From the ExitStatus::code documentation:222- "On Unix, this will return None if the process was terminated by a signal."223- In that case, ExitStatusExt::signal should never return None.224- */225- status.code().or_else(||226- /* To differentiate between "normal" exit codes and signals, we are using227- something similar to bash exit codes (https://tldp.org/LDP/abs/html/exitcodes.html)228- by adding 128 to a signal integer value.229- */230- status.signal().map(|s| 128 + s))231-}232-233-#[cfg(not(unix))]234-fn extract_exit_code(status: ExitStatus) -> Option<i32> {235- status.code()236-}237-238-/// Run the benchmark for a single shell command239-pub fn run_benchmark(240- num: usize,241- cmd: &Command<'_>,242- shell_spawning_time: TimingResult,243- options: &Options,244-) -> Result<BenchmarkResult> {245- let command_name = cmd.get_name();246- if options.output_style != OutputStyleOption::Disabled {247- println!(248- "{}{}: {}",249- "Benchmark ".bold(),250- (num + 1).to_string().bold(),251- command_name,252- );253- }254-255- let mut times_real: Vec<Second> = vec![];256- let mut times_user: Vec<Second> = vec![];257- let mut times_system: Vec<Second> = vec![];258- let mut exit_codes: Vec<Option<i32>> = vec![];259- let mut all_succeeded = true;260-261- // Run init command262- let prepare_cmd = options.preparation_command.as_ref().map(|values| {263- let preparation_command = if values.len() == 1 {264- &values[0]265- } else {266- &values[num]267- };268- Command::new_parametrized(None, preparation_command, cmd.get_parameters().clone())269- });270-271- // Run setup command272- let setup_cmd = options.setup_command.as_ref().map(|setup_command| {273- Command::new_parametrized(None, setup_command, cmd.get_parameters().clone())274- });275- run_setup_command(&options.shell, &setup_cmd, options.show_output)?;276-277- // Warmup phase278- if options.warmup_count > 0 {279- let progress_bar = if options.output_style != OutputStyleOption::Disabled {280- Some(get_progress_bar(281- options.warmup_count,282- "Performing warmup runs",283- options.output_style,284- ))285- } else {286- None287- };288-289- for _ in 0..options.warmup_count {290- let _ = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;291- let _ = time_shell_command(292- &options.shell,293- cmd,294- options.show_output,295- options.failure_action,296- None,297- )?;298- if let Some(bar) = progress_bar.as_ref() {299- bar.inc(1)300- }301- }302- if let Some(bar) = progress_bar.as_ref() {303- bar.finish_and_clear()304- }305- }306-307- // Set up progress bar (and spinner for initial measurement)308- let progress_bar = if options.output_style != OutputStyleOption::Disabled {309- Some(get_progress_bar(310- options.runs.min,311- "Initial time measurement",312- options.output_style,313- ))314- } else {315- None316- };317-318- let prepare_res = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;319-320- // Initial timing run321- let (res, status) = time_shell_command(322- &options.shell,323- cmd,324- options.show_output,325- options.failure_action,326- Some(shell_spawning_time),327- )?;328- let success = status.success();329-330- // Determine number of benchmark runs331- let runs_in_min_time = (options.min_time_sec332- / (res.time_real + prepare_res.time_real + shell_spawning_time.time_real))333- as u64;334-335- let count = {336- let min = cmp::max(runs_in_min_time, options.runs.min);337-338- options339- .runs340- .max341- .as_ref()342- .map(|max| cmp::min(min, *max))343- .unwrap_or(min)344- };345-346- let count_remaining = count - 1;347-348- // Save the first result349- times_real.push(res.time_real);350- times_user.push(res.time_user);351- times_system.push(res.time_system);352- exit_codes.push(extract_exit_code(status));353-354- all_succeeded = all_succeeded && success;355-356- // Re-configure the progress bar357- if let Some(bar) = progress_bar.as_ref() {358- bar.set_length(count)359- }360- if let Some(bar) = progress_bar.as_ref() {361- bar.inc(1)362- }363-364- // Gather statistics365- for _ in 0..count_remaining {366- run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;367-368- let msg = {369- let mean = format_duration(mean(×_real), options.time_unit);370- format!("Current estimate: {}", mean.to_string().green())371- };372-373- if let Some(bar) = progress_bar.as_ref() {374- bar.set_message(msg.to_owned())375- }376-377- let (res, status) = time_shell_command(378- &options.shell,379- cmd,380- options.show_output,381- options.failure_action,382- Some(shell_spawning_time),383- )?;384- let success = status.success();385-386- times_real.push(res.time_real);387- times_user.push(res.time_user);388- times_system.push(res.time_system);389- exit_codes.push(extract_exit_code(status));390-391- all_succeeded = all_succeeded && success;392-393- if let Some(bar) = progress_bar.as_ref() {394- bar.inc(1)395- }396- }397-398- if let Some(bar) = progress_bar.as_ref() {399- bar.finish_and_clear()400- }401-402- // Compute statistical quantities403- let t_num = times_real.len();404- let t_mean = mean(×_real);405- let t_stddev = if times_real.len() > 1 {406- Some(standard_deviation(×_real, Some(t_mean)))407- } else {408- None409- };410- let t_median = median(×_real);411- let t_min = min(×_real);412- let t_max = max(×_real);413-414- let user_mean = mean(×_user);415- let system_mean = mean(×_system);416-417- // Formatting and console output418- let (mean_str, time_unit) = format_duration_unit(t_mean, options.time_unit);419- let min_str = format_duration(t_min, Some(time_unit));420- let max_str = format_duration(t_max, Some(time_unit));421- let num_str = format!("{} runs", t_num);422-423- let user_str = format_duration(user_mean, Some(time_unit));424- let system_str = format_duration(system_mean, Some(time_unit));425-426- if options.output_style != OutputStyleOption::Disabled {427- if times_real.len() == 1 {428- println!(429- " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",430- "abs".green().bold(),431- mean_str.green().bold(),432- " ".to_string(), // alignment433- user_str.blue(),434- system_str.blue()435- );436- } else {437- let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));438-439- println!(440- " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",441- "mean".green().bold(),442- "σ".green(),443- mean_str.green().bold(),444- stddev_str.green(),445- user_str.blue(),446- system_str.blue()447- );448-449- println!(450- " Range ({} … {}): {:>8} … {:>8} {}",451- "min".cyan(),452- "max".purple(),453- min_str.cyan(),454- max_str.purple(),455- num_str.dimmed()456- );457- }458- }459-460- // Warnings461- let mut warnings = vec![];462-463- // Check execution time464- if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {465- warnings.push(Warnings::FastExecutionTime);466- }467-468- // Check programm exit codes469- if !all_succeeded {470- warnings.push(Warnings::NonZeroExitCode);471- }472-473- // Run outlier detection474- let scores = modified_zscores(×_real);475- if scores[0] > OUTLIER_THRESHOLD {476- warnings.push(Warnings::SlowInitialRun(times_real[0]));477- } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {478- warnings.push(Warnings::OutliersDetected);479- }480-481- if !warnings.is_empty() {482- eprintln!(" ");483-484- for warning in &warnings {485- eprintln!(" {}: {}", "Warning".yellow(), warning);486- }487- }488-489- if options.output_style != OutputStyleOption::Disabled {490- println!(" ");491- }492-493- // Run cleanup command494- let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {495- Command::new_parametrized(None, cleanup_command, cmd.get_parameters().clone())496- });497- run_cleanup_command(&options.shell, &cleanup_cmd, options.show_output)?;498-499- Ok(BenchmarkResult {500- command: command_name,501- mean: t_mean,502- stddev: t_stddev,503- median: t_median,504- user: user_mean,505- system: system_mean,506- min: t_min,507- max: t_max,508- times: Some(times_real),509- exit_codes,510- parameters: cmd511- .get_parameters()512- .iter()513- .map(|(name, value)| ((*name).to_string(), value.to_string()))514- .collect(),515- })516-}modified:src/main.rs+1 added-2 removed
2 unmodified lines3 use colored::*;4 5 pub mod app;6 pub mod benchmark;7-pub mod benchmark_result;7 pub mod command;8 pub mod error;9 pub mod export;10 pub mod format;10 unmodified lines21 pub mod units;22 pub mod warnings;23 24 use app::get_arg_matches;25+use benchmark::result::BenchmarkResult;26 use benchmark::{mean_shell_spawning_time, run_benchmark};27-use benchmark_result::BenchmarkResult;27 use command::{build_commands, Command};28 use export::ExportManager;29 use options::{Options, OutputStyleOption};30 97 unmodified linesmodified:src/relative_speed.rs+2 added-1 removed
1 use std::cmp::Ordering;2 3-use crate::{benchmark_result::BenchmarkResult, units::Scalar};3+use crate::benchmark::result::BenchmarkResult;4+use crate::units::Scalar;5 6 #[derive(Debug)]7 pub struct BenchmarkResultWithRelativeSpeed<'a> {8 pub result: &'a BenchmarkResult,92 unmodified lines