Skip to content
Myr

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

11 files+572 added−570 removed

added:src/benchmark/mod.rs+518 added
1pub mod result;23use std::cmp;4use std::process::{ExitStatus, Stdio};56use colored::*;7use statistical::{mean, median, standard_deviation};89use crate::benchmark::result::BenchmarkResult;10use crate::command::Command;11use crate::format::{format_duration, format_duration_unit};12use crate::min_max::{max, min};13use crate::options::{CmdFailureAction, Options, OutputStyleOption, Shell};14use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};15use crate::progress_bar::get_progress_bar;16use crate::shell::execute_and_time;17use crate::timer::wallclocktimer::WallClockTimer;18use crate::timer::{TimerStart, TimerStop};19use crate::units::Second;20use crate::warnings::Warnings;2122use anyhow::{bail, Result};2324/// Threshold for warning about fast execution time25pub const MIN_EXECUTION_TIME: Second = 5e-3;2627/// Results from timing a single shell command28#[derive(Debug, Default, Copy, Clone)]29pub struct TimingResult {30 /// Wall clock time31 pub time_real: Second,3233 /// Time spent in user mode34 pub time_user: Second,3536 /// Time spent in kernel mode37 pub time_system: Second,38}3940/// Correct for shell spawning time41fn 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}4849/// Run the given shell command and measure the execution time50pub 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 };6263 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();6667 let mut time_user = result.user_time;68 let mut time_system = result.system_time;6970 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 }8081 // 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 }8788 Ok((89 TimingResult {90 time_real,91 time_user,92 time_system,93 },94 result.status,95 ))96}9798/// Measure the average shell spawning time99pub 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 };114115 let mut times_real: Vec<Second> = vec![];116 let mut times_user: Vec<Second> = vec![];117 let mut times_system: Vec<Second> = vec![];118119 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 );128129 match res {130 Err(_) => {131 let shell_cmd = if cfg!(windows) {132 format!("{} /C \"\"", shell)133 } else {134 format!("{} -c \"\"", shell)135 };136137 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 }148149 if let Some(bar) = progress_bar.as_ref() {150 bar.inc(1)151 }152 }153154 if let Some(bar) = progress_bar.as_ref() {155 bar.finish_and_clear()156 }157158 Ok(TimingResult {159 time_real: mean(&times_real),160 time_user: mean(&times_user),161 time_system: mean(&times_system),162 })163}164165fn 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}182183/// Run the command specified by `--setup`.184fn 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.";191192 run_intermediate_command(shell, command, show_output, error_output)193}194195/// Run the command specified by `--prepare`.196fn 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.";203204 run_intermediate_command(shell, command, show_output, error_output)205}206207/// Run the command specified by `--cleanup`.208fn 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.";215216 run_intermediate_command(shell, command, show_output, error_output)217}218219#[cfg(unix)]220fn extract_exit_code(status: ExitStatus) -> Option<i32> {221 use std::os::unix::process::ExitStatusExt;222223 /* 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}234235#[cfg(not(unix))]236fn extract_exit_code(status: ExitStatus) -> Option<i32> {237 status.code()238}239240/// Run the benchmark for a single shell command241pub 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 }256257 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;262263 // 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 });272273 // 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)?;278279 // 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 };290291 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 }308309 // 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 };319320 let prepare_res = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;321322 // 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();331332 // 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;336337 let count = {338 let min = cmp::max(runs_in_min_time, options.runs.min);339340 options341 .runs342 .max343 .as_ref()344 .map(|max| cmp::min(min, *max))345 .unwrap_or(min)346 };347348 let count_remaining = count - 1;349350 // 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));355356 all_succeeded = all_succeeded && success;357358 // 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 }365366 // Gather statistics367 for _ in 0..count_remaining {368 run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;369370 let msg = {371 let mean = format_duration(mean(&times_real), options.time_unit);372 format!("Current estimate: {}", mean.to_string().green())373 };374375 if let Some(bar) = progress_bar.as_ref() {376 bar.set_message(msg.to_owned())377 }378379 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();387388 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));392393 all_succeeded = all_succeeded && success;394395 if let Some(bar) = progress_bar.as_ref() {396 bar.inc(1)397 }398 }399400 if let Some(bar) = progress_bar.as_ref() {401 bar.finish_and_clear()402 }403404 // Compute statistical quantities405 let t_num = times_real.len();406 let t_mean = mean(&times_real);407 let t_stddev = if times_real.len() > 1 {408 Some(standard_deviation(&times_real, Some(t_mean)))409 } else {410 None411 };412 let t_median = median(&times_real);413 let t_min = min(&times_real);414 let t_max = max(&times_real);415416 let user_mean = mean(&times_user);417 let system_mean = mean(&times_system);418419 // 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);424425 let user_str = format_duration(user_mean, Some(time_unit));426 let system_str = format_duration(system_mean, Some(time_unit));427428 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));440441 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 );450451 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 }461462 // Warnings463 let mut warnings = vec![];464465 // Check execution time466 if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {467 warnings.push(Warnings::FastExecutionTime);468 }469470 // Check programm exit codes471 if !all_succeeded {472 warnings.push(Warnings::NonZeroExitCode);473 }474475 // Run outlier detection476 let scores = modified_zscores(&times_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 }482483 if !warnings.is_empty() {484 eprintln!(" ");485486 for warning in &warnings {487 eprintln!(" {}: {}", "Warning".yellow(), warning);488 }489 }490491 if options.output_style != OutputStyleOption::Disabled {492 println!(" ");493 }494495 // 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)?;500501 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
1use std::collections::BTreeMap;23use serde::Serialize;45use crate::units::Second;67/// 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)]11pub struct BenchmarkResult {12 /// The command that was run13 pub command: String,1415 /// The mean run time16 pub mean: Second,1718 /// The standard deviation of all run times. Not available if only one run has been performed19 pub stddev: Option<Second>,2021 /// The median run time22 pub median: Second,2324 /// Time spend in user space25 pub user: Second,2627 /// Time spent in system space28 pub system: Second,2930 /// Min time measured31 pub min: Second,3233 /// Max time measured34 pub max: Second,3536 /// All run time measurements37 #[serde(skip_serializing_if = "Option::is_none")]38 pub times: Option<Vec<Second>>,3940 /// All run exit codes41 pub exit_codes: Vec<Option<i32>>,4243 /// 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
1use crate::benchmark_result::BenchmarkResult;1use crate::benchmark::result::BenchmarkResult;2use crate::format::format_duration_value;3use crate::relative_speed::{self, BenchmarkResultWithRelativeSpeed};4use crate::units::Unit;5
268 unmodified lines
modified:src/export/csv.rs+1 added-1 removed
1 unmodified line
23use csv::WriterBuilder;45use super::Exporter;6use crate::benchmark_result::BenchmarkResult;6use crate::benchmark::result::BenchmarkResult;7use crate::units::Unit;89use anyhow::Result;10
100 unmodified lines
modified:src/export/json.rs+1 added-1 removed
1use serde::*;2use serde_json::to_vec_pretty;34use super::Exporter;5use crate::benchmark_result::BenchmarkResult;5use crate::benchmark::result::BenchmarkResult;6use crate::units::Unit;78use anyhow::Result;9
18 unmodified lines
modified:src/export/markdown.rs+1 added-1 removed
1use super::Exporter;2use crate::benchmark_result::BenchmarkResult;2use crate::benchmark::result::BenchmarkResult;3use crate::format::format_duration_value;4use crate::relative_speed::{self, BenchmarkResultWithRelativeSpeed};5use crate::units::Unit;6
287 unmodified lines
modified:src/export/mod.rs+1 added-1 removed
9 unmodified lines
10use self::csv::CsvExporter;11use self::json::JsonExporter;12use self::markdown::MarkdownExporter;1314use crate::benchmark_result::BenchmarkResult;14use crate::benchmark::result::BenchmarkResult;15use crate::units::Unit;1617use anyhow::{Context, Result};18use clap::ArgMatches;
89 unmodified lines
deleted:src/benchmark_result.rs-46 removed
1use std::collections::BTreeMap;23use serde::Serialize;45use crate::units::Second;67/// 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)]11pub struct BenchmarkResult {12 /// The command that was run13 pub command: String,1415 /// The mean run time16 pub mean: Second,1718 /// The standard deviation of all run times. Not available if only one run has been performed19 pub stddev: Option<Second>,2021 /// The median run time22 pub median: Second,2324 /// Time spend in user space25 pub user: Second,2627 /// Time spent in system space28 pub system: Second,2930 /// Min time measured31 pub min: Second,3233 /// Max time measured34 pub max: Second,3536 /// All run time measurements37 #[serde(skip_serializing_if = "Option::is_none")]38 pub times: Option<Vec<Second>>,3940 /// All run exit codes41 pub exit_codes: Vec<Option<i32>>,4243 /// Any parameter values used44 #[serde(skip_serializing_if = "BTreeMap::is_empty")]45 pub parameters: BTreeMap<String, String>,46}
deleted:src/benchmark.rs-516 removed
1use std::cmp;2use std::process::{ExitStatus, Stdio};34use colored::*;5use statistical::{mean, median, standard_deviation};67use crate::benchmark_result::BenchmarkResult;8use crate::command::Command;9use crate::format::{format_duration, format_duration_unit};10use crate::min_max::{max, min};11use crate::options::{CmdFailureAction, Options, OutputStyleOption, Shell};12use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};13use crate::progress_bar::get_progress_bar;14use crate::shell::execute_and_time;15use crate::timer::wallclocktimer::WallClockTimer;16use crate::timer::{TimerStart, TimerStop};17use crate::units::Second;18use crate::warnings::Warnings;1920use anyhow::{bail, Result};2122/// Threshold for warning about fast execution time23pub const MIN_EXECUTION_TIME: Second = 5e-3;2425/// Results from timing a single shell command26#[derive(Debug, Default, Copy, Clone)]27pub struct TimingResult {28 /// Wall clock time29 pub time_real: Second,3031 /// Time spent in user mode32 pub time_user: Second,3334 /// Time spent in kernel mode35 pub time_system: Second,36}3738/// Correct for shell spawning time39fn 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}4647/// Run the given shell command and measure the execution time48pub 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 };6061 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();6465 let mut time_user = result.user_time;66 let mut time_system = result.system_time;6768 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 }7879 // 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 }8586 Ok((87 TimingResult {88 time_real,89 time_user,90 time_system,91 },92 result.status,93 ))94}9596/// Measure the average shell spawning time97pub 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 };112113 let mut times_real: Vec<Second> = vec![];114 let mut times_user: Vec<Second> = vec![];115 let mut times_system: Vec<Second> = vec![];116117 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 );126127 match res {128 Err(_) => {129 let shell_cmd = if cfg!(windows) {130 format!("{} /C \"\"", shell)131 } else {132 format!("{} -c \"\"", shell)133 };134135 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 }146147 if let Some(bar) = progress_bar.as_ref() {148 bar.inc(1)149 }150 }151152 if let Some(bar) = progress_bar.as_ref() {153 bar.finish_and_clear()154 }155156 Ok(TimingResult {157 time_real: mean(&times_real),158 time_user: mean(&times_user),159 time_system: mean(&times_system),160 })161}162163fn 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}180181/// Run the command specified by `--setup`.182fn 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.";189190 run_intermediate_command(shell, command, show_output, error_output)191}192193/// Run the command specified by `--prepare`.194fn 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.";201202 run_intermediate_command(shell, command, show_output, error_output)203}204205/// Run the command specified by `--cleanup`.206fn 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.";213214 run_intermediate_command(shell, command, show_output, error_output)215}216217#[cfg(unix)]218fn extract_exit_code(status: ExitStatus) -> Option<i32> {219 use std::os::unix::process::ExitStatusExt;220221 /* 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}232233#[cfg(not(unix))]234fn extract_exit_code(status: ExitStatus) -> Option<i32> {235 status.code()236}237238/// Run the benchmark for a single shell command239pub 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 }254255 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;260261 // 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 });270271 // 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)?;276277 // 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 };288289 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 }306307 // 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 };317318 let prepare_res = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;319320 // 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();329330 // 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;334335 let count = {336 let min = cmp::max(runs_in_min_time, options.runs.min);337338 options339 .runs340 .max341 .as_ref()342 .map(|max| cmp::min(min, *max))343 .unwrap_or(min)344 };345346 let count_remaining = count - 1;347348 // 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));353354 all_succeeded = all_succeeded && success;355356 // 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 }363364 // Gather statistics365 for _ in 0..count_remaining {366 run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;367368 let msg = {369 let mean = format_duration(mean(&times_real), options.time_unit);370 format!("Current estimate: {}", mean.to_string().green())371 };372373 if let Some(bar) = progress_bar.as_ref() {374 bar.set_message(msg.to_owned())375 }376377 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();385386 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));390391 all_succeeded = all_succeeded && success;392393 if let Some(bar) = progress_bar.as_ref() {394 bar.inc(1)395 }396 }397398 if let Some(bar) = progress_bar.as_ref() {399 bar.finish_and_clear()400 }401402 // Compute statistical quantities403 let t_num = times_real.len();404 let t_mean = mean(&times_real);405 let t_stddev = if times_real.len() > 1 {406 Some(standard_deviation(&times_real, Some(t_mean)))407 } else {408 None409 };410 let t_median = median(&times_real);411 let t_min = min(&times_real);412 let t_max = max(&times_real);413414 let user_mean = mean(&times_user);415 let system_mean = mean(&times_system);416417 // 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);422423 let user_str = format_duration(user_mean, Some(time_unit));424 let system_str = format_duration(system_mean, Some(time_unit));425426 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));438439 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 );448449 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 }459460 // Warnings461 let mut warnings = vec![];462463 // Check execution time464 if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {465 warnings.push(Warnings::FastExecutionTime);466 }467468 // Check programm exit codes469 if !all_succeeded {470 warnings.push(Warnings::NonZeroExitCode);471 }472473 // Run outlier detection474 let scores = modified_zscores(&times_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 }480481 if !warnings.is_empty() {482 eprintln!(" ");483484 for warning in &warnings {485 eprintln!(" {}: {}", "Warning".yellow(), warning);486 }487 }488489 if options.output_style != OutputStyleOption::Disabled {490 println!(" ");491 }492493 // 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)?;498499 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 lines
3use colored::*;45pub mod app;6pub mod benchmark;7pub mod benchmark_result;7pub mod command;8pub mod error;9pub mod export;10pub mod format;
10 unmodified lines
21pub mod units;22pub mod warnings;2324use app::get_arg_matches;25use benchmark::result::BenchmarkResult;26use benchmark::{mean_shell_spawning_time, run_benchmark};27use benchmark_result::BenchmarkResult;27use command::{build_commands, Command};28use export::ExportManager;29use options::{Options, OutputStyleOption};30
97 unmodified lines
modified:src/relative_speed.rs+2 added-1 removed
1use std::cmp::Ordering;23use crate::{benchmark_result::BenchmarkResult, units::Scalar};3use crate::benchmark::result::BenchmarkResult;4use crate::units::Scalar;56#[derive(Debug)]7pub struct BenchmarkResultWithRelativeSpeed<'a> {8 pub result: &'a BenchmarkResult,
92 unmodified lines