Skip to content
Myr

Handling of errors and warnings

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by sharkdp · committed by sharkdp · parent 219bb1e · Browse files · 3 files+69 added−34 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+69 added−34 removed

  • other:+69 added−34 removed

3 files+69 added−34 removed

modified:src/main.rs+67 added-32 removed
6 unmodified lines
7use std::error::Error;8use std::io;9use std::process::{Command, Stdio};10use std::time::Instant;11use std::fmt;1213use indicatif::{ProgressBar, ProgressStyle};13use ansi_term::Colour::{Cyan, Green, Red};14use ansi_term::Colour::{Cyan, Green, Yellow};15use clap::{App, AppSettings, Arg};1617/// Type alias for unit of time18type Second = f64;1920/// Threshold for warning about fast execution time21const MIN_EXECUTION_TIME: Second = 5e-3;2223/// Print error message to stderr and terminate24pub fn error(message: &str) -> ! {25 eprintln!("{}", message);26 std::process::exit(1);27}2829struct CmdResult {30 /// Execution time in seconds24 execution_time_sec: f64,31 execution_time_sec: Second,3233 /// True if the command finished with exit code zero34 success: bool,35}3637impl CmdResult {31 fn new(execution_time_sec: f64, success: bool) -> CmdResult {38 fn new(execution_time_sec: Second, success: bool) -> CmdResult {39 CmdResult {40 execution_time_sec,41 success,42 }
14 unmodified lines
57 let duration = start.elapsed();5859 let execution_time_sec = duration.as_secs() as f64 + duration.subsec_nanos() as f64 * 1e-9;6054 const MILLISECOND: f64 = 1e-3;55 if execution_time_sec < MILLISECOND {56 Err(io::Error::new(io::ErrorKind::Other, format!{57 "Command took only {:.6} s to complete. Execution is probably dominated by shell overhead.",58 execution_time_sec59 }))60 } else {61 Ok(CmdResult::new(execution_time_sec, status.success()))61 Ok(CmdResult::new(execution_time_sec, status.success()))62 }62}6364/// Return a pre-configured progress bar65fn get_progress_bar(length: u64, msg: &str) -> ProgressBar {
8 unmodified lines
7475 bar76}7778/// Possible benchmark warnings79enum Warnings {80 FastExecutionTime,81 NonZeroExitCode,82}8384impl fmt::Display for Warnings {85 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {86 match self {87 &Warnings::FastExecutionTime => write!(88 f,89 "Command took less than {:.0} ms to complete. \90 The execution time is likely to be dominated by the intermediate shell.",91 MIN_EXECUTION_TIME * 1e392 ),93 &Warnings::NonZeroExitCode => write!(f, "Process exited with a non-zero exit code"),94 }95 }96}9798/// Run the benchmark for a single shell command80fn run_benchmark(cmd: &str, options: &HyperfineOptions) {99fn run_benchmark(cmd: &str, options: &HyperfineOptions) -> io::Result<()> {100 println!("Command: {}", Cyan.paint(cmd));101 println!();102103 let mut results = vec![];
12 unmodified lines
116 // Set up progress bar (and spinner for initial measurement)117 let bar = get_progress_bar(options.min_runs, "Initial time measurement");118119 // Initial timing run101 let res = match time_shell_command(cmd) {102 Ok(s) => s,103 Err(e) => error(e.description()),104 };120 let res = time_shell_command(cmd)?;121122 let runs_in_min_time = (options.min_time_sec / res.execution_time_sec) as u64;123124 let count = if runs_in_min_time >= options.min_runs {
11 unmodified lines
136137 // Gather statistics138 for _ in 1..count {139 bar.inc(1);124 let res = match time_shell_command(cmd) {125 Ok(s) => s,126 Err(e) => error(e.description()),127 };140 let res = time_shell_command(cmd)?;141 results.push(res);142 }143 bar.finish_and_clear();144145 // Compute statistical quantities133 let t_sum: f64 = results.iter().map(|r| r.execution_time_sec).sum();146 let get_execution_time = |r: &CmdResult| -> Second { r.execution_time_sec };147148 // Iterator over execution times149 let execution_times = results.iter().map(&get_execution_time);150151 let t_sum: Second = execution_times.clone().sum();152 let t_mean = t_sum / (results.len() as f64);153136 let t2_sum: f64 = results.iter().map(|r| r.execution_time_sec.powi(2)).sum();154 let t2_sum: Second = execution_times.clone().map(|t| t.powi(2)).sum();155 let t2_mean = t2_sum / (results.len() as f64);156157 let stddev = (t2_mean - t_mean.powi(2)).sqrt();158
1 unmodified line
160 let time_fmt = format!("{:.3} s ± {:.3} s", t_mean, stddev);161162 println!(" Time: {}", Green.paint(time_fmt));163146 if !results.iter().all(|r| r.success) {147 println!(148 " {}: Program returned non-zero exit status",149 Red.paint("Warning")150 );151 };164 // Warnings165 let mut warnings = vec![];166167 // Check execution time168 if execution_times.clone().any(|t| t < MIN_EXECUTION_TIME) {169 warnings.push(Warnings::FastExecutionTime);170 }171172 // Check programm exit codes173 if results.iter().any(|r| !r.success) {174 warnings.push(Warnings::NonZeroExitCode);175 }176177 for warning in &warnings {178 eprintln!(" {}: {}", Yellow.paint("Warning"), warning);179 }180181 println!();182183 Ok(())184}185186pub struct HyperfineOptions {187 pub warmup_count: Option<u64>,188 pub min_runs: u64,159 pub min_time_sec: f64,189 pub min_time_sec: Second,190}191192impl Default for HyperfineOptions {193 fn default() -> HyperfineOptions {194 HyperfineOptions {195 warmup_count: None,196 min_runs: 10,167 min_time_sec: 5.0,197 min_time_sec: 3.0,198 }199 }200}201
40 unmodified lines
242243 // Run the benchmarks244 let commands = matches.values_of("command").unwrap();245 for cmd in commands {216 run_benchmark(&cmd, &options);246 let res = run_benchmark(&cmd, &options);247248 match res {249 Err(err) => error(err.description()),250 Ok(_) => {}251 }252 }253}
modified:Cargo.lock+1 added-1 removed
81 unmodified lines
82source = "registry+https://github.com/rust-lang/crates.io-index"8384[[package]]85name = "hyperfine"86version = "0.1.0"86version = "0.2.0"87dependencies = [88 "ansi_term 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)",89 "clap 2.29.1 (registry+https://github.com/rust-lang/crates.io-index)",90 "indicatif 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
266 unmodified lines
modified:Cargo.toml+1 added-1 removed