Fix nan/inf output for very fast commands
Before adoption: this commit came in with the history the project adopted, so no landing records it.
closes #319
authored by sharkdp · committed by David Peter · parent 314e4e3 · Browse files · 4 files·+103 added−61 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+103 added−61 removed
- other:+103 added−61 removed
Provenance
- Commit
b2a246c- Tree
1781f4f- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
314e4e3
4 files changed+103 added−61 removed
modified:src/hyperfine/export/markdown.rs+12 added-7 removed
3 unmodified lines4 use crate::hyperfine::internal::{compute_relative_speed, BenchmarkResultWithRelativeSpeed};5 use crate::hyperfine::types::BenchmarkResult;6 use crate::hyperfine::units::Unit;7 8-use std::io::Result;8+use std::io::{Error, ErrorKind, Result};9 10 #[derive(Default)]11 pub struct MarkdownExporter {}12 9 unmodified lines22 // Default to `Second`.23 Unit::Second24 };25 26- let annotated_results = compute_relative_speed(results);26+ if let Some(annotated_results) = compute_relative_speed(results) {27+ let mut destination = start_table(unit);28 28- let mut destination = start_table(unit);29+ for result in annotated_results {30+ add_table_row(&mut destination, &result, unit);31+ }32 30- for result in annotated_results {31- add_table_row(&mut destination, &result, unit);33+ Ok(destination)34+ } else {35+ Err(Error::new(36+ ErrorKind::Other,37+ "Relative speed comparison is not available for Markdown export.",38+ ))39 }33-34- Ok(destination)40 }41 }42 43 fn table_header(unit_short_name: String) -> String {242 unmodified linesmodified:src/hyperfine/internal.rs+66 added-35 removed
50 unmodified lines51 .min_by(|a, b| a.partial_cmp(b).unwrap())52 .unwrap()53 }54 55+#[derive(Debug)]56 pub struct BenchmarkResultWithRelativeSpeed<'a> {57 pub result: &'a BenchmarkResult,58 pub relative_speed: Scalar,59 pub relative_speed_stddev: Scalar,5 unmodified lines65 }66 67 pub fn compute_relative_speed<'a>(68 results: &'a [BenchmarkResult],68-) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> {69+) -> Option<Vec<BenchmarkResultWithRelativeSpeed<'a>>> {70 let fastest: &BenchmarkResult = results71 .iter()72 .min_by(|&l, &r| compare_mean_time(l, r))73 .expect("at least one benchmark result");74 74- results75- .iter()76- .map(|result| {77- let ratio = result.mean / fastest.mean;75+ if fastest.mean == 0.0 {76+ return None;77+ }78 79+ Some(80+ results81+ .iter()82+ .map(|result| {83+ let ratio = result.mean / fastest.mean;84+79- // https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas80- // Covariance asssumed to be 0, i.e. variables are assumed to be independent81- let ratio_stddev = ratio82- * ((result.stddev / result.mean).powi(2) + (fastest.stddev / fastest.mean).powi(2))85+ // https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas86+ // Covariance asssumed to be 0, i.e. variables are assumed to be independent87+ let ratio_stddev = ratio88+ * ((result.stddev / result.mean).powi(2)89+ + (fastest.stddev / fastest.mean).powi(2))90 .sqrt();91 85- BenchmarkResultWithRelativeSpeed {86- result,87- relative_speed: ratio,88- relative_speed_stddev: ratio_stddev,89- is_fastest: result == fastest,90- }91- })92- .collect()92+ BenchmarkResultWithRelativeSpeed {93+ result,94+ relative_speed: ratio,95+ relative_speed_stddev: ratio_stddev,96+ is_fastest: result == fastest,97+ }98+ })99+ .collect(),100+ )101 }102 103 pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {104 if results.len() < 2 {105 return;106 }107 100- let mut annotated_results = compute_relative_speed(&results);101- annotated_results.sort_by(|l, r| compare_mean_time(l.result, r.result));108+ if let Some(mut annotated_results) = compute_relative_speed(&results) {109+ annotated_results.sort_by(|l, r| compare_mean_time(l.result, r.result));110 103- let fastest = &annotated_results[0];104- let others = &annotated_results[1..];111+ let fastest = &annotated_results[0];112+ let others = &annotated_results[1..];113 106- println!("{}", "Summary".bold());107- println!(" '{}' ran", fastest.result.command.cyan());114+ println!("{}", "Summary".bold());115+ println!(" '{}' ran", fastest.result.command.cyan());116 109- for item in others {110- println!(111- "{} ± {} times faster than '{}'",112- format!("{:8.2}", item.relative_speed).bold().green(),113- format!("{:.2}", item.relative_speed_stddev).green(),114- &item.result.command.magenta()117+ for item in others {118+ println!(119+ "{} ± {} times faster than '{}'",120+ format!("{:8.2}", item.relative_speed).bold().green(),121+ format!("{:.2}", item.relative_speed_stddev).green(),122+ &item.result.command.magenta()123+ );124+ }125+ } else {126+ eprintln!(127+ "{}: The benchmark comparison could not be computed as some benchmark times are zero. \128+ This could be caused by background interference during the initial calibration phase \129+ of hyperfine, in combination with very fast commands (faster than a few milliseconds). \130+ Try to re-run the benchmark on a quiet system. If it does not help, you command is \131+ most likely too fast to be accurately benchmarked by hyperfine.",132+ "Note".bold().red()133 );134 }135 }136 5 unmodified lines142 assert_eq!(1.0, max(&[-1.0, 1.0]));143 assert_eq!(1.0, max(&[-1.0, 1.0, 0.0]));144 }145 128-#[test]129-fn test_compute_relative_speed() {130- use approx::assert_relative_eq;146+#[cfg(test)]147+fn create_result(name: &str, mean: Scalar) -> BenchmarkResult {148 use std::collections::BTreeMap;149 133- let create_result = |name: &str, mean| BenchmarkResult {150+ BenchmarkResult {151 command: name.into(),152 mean,153 stddev: 1.0,154 median: mean,2 unmodified lines157 min: mean,158 max: mean,159 times: None,160 parameters: BTreeMap::new(),144- };161+ }162+}163 164+#[test]165+fn test_compute_relative_speed() {166+ use approx::assert_relative_eq;167+168 let results = vec![169 create_result("cmd1", 3.0),170 create_result("cmd2", 2.0),171 create_result("cmd3", 5.0),172 ];173 152- let annotated_results = compute_relative_speed(&results);174+ let annotated_results = compute_relative_speed(&results).unwrap();175 176 assert_relative_eq!(1.5, annotated_results[0].relative_speed);177 assert_relative_eq!(1.0, annotated_results[1].relative_speed);178 assert_relative_eq!(2.5, annotated_results[2].relative_speed);179 }180 181+#[test]182+fn test_compute_relative_speed_for_zero_times() {183+ let results = vec![create_result("cmd1", 1.0), create_result("cmd2", 0.0)];184+185+ let annotated_results = compute_relative_speed(&results);186+187+ assert!(annotated_results.is_none());188+}189+190 pub fn tokenize<'a>(values: &'a str) -> Vec<String> {191 let mut tokens = vec![];192 let mut buf = String::new();193 56 unmodified linesmodified:src/main.rs+23 added-19 removed
14 unmodified lines15 use crate::hyperfine::export::{ExportManager, ExportType};16 use crate::hyperfine::internal::{tokenize, write_benchmark_comparison};17 use crate::hyperfine::parameter_range::get_parameterized_commands;18 use crate::hyperfine::types::{19- BenchmarkResult, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption, ParameterValue,19+ CmdFailureAction, Command, HyperfineOptions, OutputStyleOption, ParameterValue,20 };21 use crate::hyperfine::units::Unit;22 23 /// Print error message to stderr and terminate2 unmodified lines26 std::process::exit(1);27 }28 29 /// Runs the benchmark for the given commands30-fn run(commands: &[Command<'_>], options: &HyperfineOptions) -> io::Result<Vec<BenchmarkResult>> {30+fn run(31+ commands: &[Command<'_>],32+ options: &HyperfineOptions,33+ export_manager: &ExportManager,34+) -> io::Result<()> {35 let shell_spawning_time =36 mean_shell_spawning_time(&options.shell, options.output_style, options.show_output)?;37 38 let mut timing_results = vec![];11 unmodified lines50 for (num, cmd) in commands.iter().enumerate() {51 timing_results.push(run_benchmark(num, cmd, shell_spawning_time, options)?);52 }53 50- Ok(timing_results)54+ // Print relative speed comparison55+ if options.output_style != OutputStyleOption::Disabled {56+ write_benchmark_comparison(&timing_results);57+ }58+59+ // Export results60+ let ans = export_manager.write_results(timing_results, options.time_unit);61+ if let Err(e) = ans {62+ error(&format!(63+ "The following error occurred while exporting: {}",64+ e65+ ));66+ }67+68+ Ok(())69 }70 71 fn main() {72 let matches = get_arg_matches(env::args_os());1 unmodified line74 let export_manager = build_export_manager(&matches);75 let commands = build_commands(&matches);76 77 let res = match options {60- Ok(ref opts) => run(&commands, &opts),78+ Ok(ref opts) => run(&commands, &opts, &export_manager),79 Err(ref e) => error(&e.to_string()),80 };81 82 match res {65- Ok(timing_results) => {66- let options = options.unwrap();67-68- if options.output_style != OutputStyleOption::Disabled {69- write_benchmark_comparison(&timing_results);70- }71-72- let ans = export_manager.write_results(timing_results, options.time_unit);73- if let Err(e) = ans {74- error(&format!(75- "The following error occurred while exporting: {}",76- e77- ));78- }79- }83+ Ok(_) => {}84 Err(e) => error(&e.to_string()),85 }86 }87 248 unmodified linesmodified:CHANGELOG.md+2 added
22 unmodified lines23 24 ## Bugfixes25 26 - Fix a bug in the outlier detection which would only detect "slow outliers" but not the fast ones (runs that are much faster than the rest of the benchmarking runs), see #32927+- Better error messages for very fast commands that would lead to inf/nan results in the relative28+ speed comparison, see #31929 - Keep output colorized when the output is not interactive and `--style=full` or `--style=color` is used.30 31 ## Other32 ## Packaging208 unmodified lines