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
Provenance
- Commit
7e41c2a- Tree
52587fe- Author
sharkdp <davidpeter@web.de>- Committer
sharkdp <davidpeter@web.de>- Parent
219bb1e
3 files changed+69 added−34 removed
modified:src/main.rs+67 added-32 removed
6 unmodified lines7 use std::error::Error;8 use std::io;9 use std::process::{Command, Stdio};10 use std::time::Instant;11+use std::fmt;12 13 use indicatif::{ProgressBar, ProgressStyle};13-use ansi_term::Colour::{Cyan, Green, Red};14+use ansi_term::Colour::{Cyan, Green, Yellow};15 use clap::{App, AppSettings, Arg};16 17+/// Type alias for unit of time18+type Second = f64;19+20+/// Threshold for warning about fast execution time21+const MIN_EXECUTION_TIME: Second = 5e-3;22+23 /// Print error message to stderr and terminate24 pub fn error(message: &str) -> ! {25 eprintln!("{}", message);26 std::process::exit(1);27 }28 29 struct CmdResult {30 /// Execution time in seconds24- execution_time_sec: f64,31+ execution_time_sec: Second,32 33 /// True if the command finished with exit code zero34 success: bool,35 }36 37 impl 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 lines57 let duration = start.elapsed();58 59 let execution_time_sec = duration.as_secs() as f64 + duration.subsec_nanos() as f64 * 1e-9;60 54- 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 }63 64 /// Return a pre-configured progress bar65 fn get_progress_bar(length: u64, msg: &str) -> ProgressBar {8 unmodified lines74 75 bar76 }77 78+/// Possible benchmark warnings79+enum Warnings {80+ FastExecutionTime,81+ NonZeroExitCode,82+}83+84+impl 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+}97+98 /// Run the benchmark for a single shell command80-fn run_benchmark(cmd: &str, options: &HyperfineOptions) {99+fn run_benchmark(cmd: &str, options: &HyperfineOptions) -> io::Result<()> {100 println!("Command: {}", Cyan.paint(cmd));101 println!();102 103 let mut results = vec![];12 unmodified lines116 // Set up progress bar (and spinner for initial measurement)117 let bar = get_progress_bar(options.min_runs, "Initial time measurement");118 119 // 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)?;121 122 let runs_in_min_time = (options.min_time_sec / res.execution_time_sec) as u64;123 124 let count = if runs_in_min_time >= options.min_runs {11 unmodified lines136 137 // 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();144 145 // 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 };147+148+ // Iterator over execution times149+ let execution_times = results.iter().map(&get_execution_time);150+151+ let t_sum: Second = execution_times.clone().sum();152 let t_mean = t_sum / (results.len() as f64);153 136- 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);156 157 let stddev = (t2_mean - t_mean.powi(2)).sqrt();158 1 unmodified line160 let time_fmt = format!("{:.3} s ± {:.3} s", t_mean, stddev);161 162 println!(" Time: {}", Green.paint(time_fmt));163 146- 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![];166 167+ // Check execution time168+ if execution_times.clone().any(|t| t < MIN_EXECUTION_TIME) {169+ warnings.push(Warnings::FastExecutionTime);170+ }171+172+ // Check programm exit codes173+ if results.iter().any(|r| !r.success) {174+ warnings.push(Warnings::NonZeroExitCode);175+ }176+177+ for warning in &warnings {178+ eprintln!(" {}: {}", Yellow.paint("Warning"), warning);179+ }180+181 println!();182+183+ Ok(())184 }185 186 pub 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 }191 192 impl 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 lines242 243 // 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);247+248+ match res {249+ Err(err) => error(err.description()),250+ Ok(_) => {}251+ }252 }253 }modified:Cargo.lock+1 added-1 removed
81 unmodified lines82 source = "registry+https://github.com/rust-lang/crates.io-index"83 84 [[package]]85 name = "hyperfine"86-version = "0.1.0"86+version = "0.2.0"87 dependencies = [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 linesmodified:Cargo.toml+1 added-1 removed
5 unmodified lines67891010111213145 unmodified lines5 unmodified lineslicense = "MIT/Apache-2.0"name = "hyperfine"readme = "README.md"repository = "https://github.com/sharkdp/hyperfine"version = "0.1.0"version = "0.2.0"
[dependencies]ansi_term = "0.10"indicatif = "0.8"5 unmodified lines