Skip to content
Myr

Add outlier detection

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

authored by sharkdp · committed by David Peter · parent cda5816 · Browse files · 4 files+128 added−0 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+128 added−0 removed

  • other:+128 added−0 removed

4 files+128 added−0 removed

modified:src/hyperfine/benchmark.rs+9 added
7 unmodified lines
8use hyperfine::internal::{get_progress_bar, max, min, CmdFailureAction, HyperfineOptions, Second,9 Warnings, MIN_EXECUTION_TIME};10use hyperfine::format::{format_duration, format_duration_unit};11use hyperfine::cputime::{cpu_time_interval, get_cpu_times};12use hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};1314/// Results from timing a single shell command15#[derive(Debug, Copy, Clone)]16pub struct TimingResult {
257 unmodified lines
274 if !all_succeeded {275 warnings.push(Warnings::NonZeroExitCode);276 }277278 // Run outlier detection279 let scores = modified_zscores(&times_real);280 if scores[0] > OUTLIER_THRESHOLD {281 warnings.push(Warnings::SlowInitialRun);282 } else if scores.iter().any(|&s| s > OUTLIER_THRESHOLD) {283 warnings.push(Warnings::OutliersDetected);284 }285286 if !warnings.is_empty() {287 eprintln!(" ");288 for warning in &warnings {289 eprintln!(" {}: {}", Yellow.paint("Warning"), warning);
7 unmodified lines
modified:src/hyperfine/internal.rs+16 added
64 unmodified lines
65/// Possible benchmark warnings66pub enum Warnings {67 FastExecutionTime,68 NonZeroExitCode,69 SlowInitialRun,70 OutliersDetected,71}7273impl fmt::Display for Warnings {74 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3 unmodified lines
78 "Command took less than {:.0} ms to complete. Results might be inaccurate.",79 MIN_EXECUTION_TIME * 1e380 ),81 Warnings::NonZeroExitCode => write!(f, "Ignoring non-zero exit code."),82 Warnings::SlowInitialRun => write!(83 f,84 "The first benchmarking run for this command was significantly slower than the \85 rest. This could be caused by (filesystem) caches that were not filled. You \86 should consider using the '--warmup' option to fill those caches before the \87 benchmark. Alternatively, use the '--prepare' option to clear the caches before \88 each timing run."89 ),90 Warnings::OutliersDetected => write!(91 f,92 "Statistical outliers were detected. Consider re-running this benchmark without \93 any interferences from other programs. It might help to use the '--warmup' or \94 '--prepare' options to mitigate outliers."95 ),96 }97 }98}99
22 unmodified lines
modified:src/hyperfine/mod.rs+1 added
1pub mod benchmark;2pub mod format;3pub mod internal;4pub mod cputime;5pub mod outlier_detection;
added:src/hyperfine/outlier_detection.rs+102 added
1/// A module for statistical outlier detection.2///3/// References:4/// - Boris Iglewicz and David Hoaglin (1993), "Volume 16: How to Detect and Handle Outliers",5/// The ASQC Basic References in Quality Control: Statistical Techniques, Edward F. Mykytka,6/// Ph.D., Editor.78use statistical::median;910/// Minimum modified Z-score for a datapoint to be an outlier. Here, 1.4826 is a factor that11/// converts the MAD to an estimator for the standard deviation. The second factor is the number12/// of standard deviations.13pub const OUTLIER_THRESHOLD: f64 = 1.4826 * 10.0;1415/// Compute modifized Z-scores for a given sample. A (unmodified) Z-score is defined by16/// (x_i - x_mean)/x_stddev whereas the modified Z-score is defined by |x_i - x_median|/MAD where17/// MAD is the median average deviation.18///19/// References:20/// - https://en.wikipedia.org/wiki/Median_absolute_deviation21pub fn modified_zscores(xs: &[f64]) -> Vec<f64> {22 assert!(!xs.is_empty());2324 // Compute sample median:25 let x_median = median(&xs);2627 // Compute the absolute deviations from the median:28 let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect();2930 // Compute median absolute deviation:31 let mad = median(&deviations);3233 // Compute modified Z-scores (x_i - x_median) / MAD34 xs.iter().map(|&x| (x - x_median) / mad).collect()35}3637/// Return the number of outliers in a given sample. Outliers are defined as data points with a38/// modified Z-score that is larger than `OUTLIER_THRESHOLD`.39#[cfg(test)]40pub fn num_outliers(xs: &[f64]) -> usize {41 if xs.is_empty() {42 return 0;43 }4445 let scores = modified_zscores(xs);46 scores47 .iter()48 .filter(|&&s| s.abs() > OUTLIER_THRESHOLD)49 .count()50}5152#[test]53fn test_detect_outliers() {54 // Should not detect outliers in small samples55 assert_eq!(0, num_outliers(&[]));56 assert_eq!(0, num_outliers(&[50.0]));57 assert_eq!(0, num_outliers(&[1000.0, 0.0]));5859 // Should not detect outliers in low-variance samples60 let xs = [-0.2, 0.0, 0.2];61 assert_eq!(0, num_outliers(&xs));6263 // Should detect a single outlier64 let xs = [-0.2, 0.0, 0.2, 4.0];65 assert_eq!(1, num_outliers(&xs));6667 // Should detect a single outlier68 let xs = [0.5, 0.30, 0.29, 0.31, 0.30];69 assert_eq!(1, num_outliers(&xs));7071 // Should detect no outliers in sample drawn from normal distribution72 let xs = [73 2.33269488,74 1.42195907,75 -0.57527698,76 -0.31293437,77 2.2948158,78 0.75813273,79 -1.0712388,80 -0.96394741,81 -1.15897446,82 1.10976285,83 ];84 assert_eq!(0, num_outliers(&xs));8586 // Should detect two outliers that were manually added87 let xs = [88 2.33269488,89 1.42195907,90 -0.57527698,91 -0.31293437,92 2.2948158,93 0.75813273,94 -1.0712388,95 -0.96394741,96 -1.15897446,97 1.10976285,98 20.0,99 -500.0,100 ];101 assert_eq!(2, num_outliers(&xs));102}