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
Provenance
- Commit
2ddc21c- Tree
5e5d251- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
cda5816
4 files changed+128 added−0 removed
modified:src/hyperfine/benchmark.rs+9 added
7 unmodified lines8 use hyperfine::internal::{get_progress_bar, max, min, CmdFailureAction, HyperfineOptions, Second,9 Warnings, MIN_EXECUTION_TIME};10 use hyperfine::format::{format_duration, format_duration_unit};11 use hyperfine::cputime::{cpu_time_interval, get_cpu_times};12+use hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};13 14 /// Results from timing a single shell command15 #[derive(Debug, Copy, Clone)]16 pub struct TimingResult {257 unmodified lines274 if !all_succeeded {275 warnings.push(Warnings::NonZeroExitCode);276 }277 278+ // Run outlier detection279+ let scores = modified_zscores(×_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+ }285+286 if !warnings.is_empty() {287 eprintln!(" ");288 for warning in &warnings {289 eprintln!(" {}: {}", Yellow.paint("Warning"), warning);7 unmodified linesmodified:src/hyperfine/internal.rs+16 added
64 unmodified lines65 /// Possible benchmark warnings66 pub enum Warnings {67 FastExecutionTime,68 NonZeroExitCode,69+ SlowInitialRun,70+ OutliersDetected,71 }72 73 impl fmt::Display for Warnings {74 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {3 unmodified lines78 "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 linesmodified:src/hyperfine/mod.rs+1 added
1 pub mod benchmark;2 pub mod format;3 pub mod internal;4 pub mod cputime;5+pub 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.7+8+use statistical::median;9+10+/// 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.13+pub const OUTLIER_THRESHOLD: f64 = 1.4826 * 10.0;14+15+/// 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_deviation21+pub fn modified_zscores(xs: &[f64]) -> Vec<f64> {22+ assert!(!xs.is_empty());23+24+ // Compute sample median:25+ let x_median = median(&xs);26+27+ // Compute the absolute deviations from the median:28+ let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect();29+30+ // Compute median absolute deviation:31+ let mad = median(&deviations);32+33+ // Compute modified Z-scores (x_i - x_median) / MAD34+ xs.iter().map(|&x| (x - x_median) / mad).collect()35+}36+37+/// 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)]40+pub fn num_outliers(xs: &[f64]) -> usize {41+ if xs.is_empty() {42+ return 0;43+ }44+45+ let scores = modified_zscores(xs);46+ scores47+ .iter()48+ .filter(|&&s| s.abs() > OUTLIER_THRESHOLD)49+ .count()50+}51+52+#[test]53+fn 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]));58+59+ // Should not detect outliers in low-variance samples60+ let xs = [-0.2, 0.0, 0.2];61+ assert_eq!(0, num_outliers(&xs));62+63+ // Should detect a single outlier64+ let xs = [-0.2, 0.0, 0.2, 4.0];65+ assert_eq!(1, num_outliers(&xs));66+67+ // Should detect a single outlier68+ let xs = [0.5, 0.30, 0.29, 0.31, 0.30];69+ assert_eq!(1, num_outliers(&xs));70+71+ // 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));85+86+ // 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+}