Skip to content
Myr

Unit safe statistics functions

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

authored by David Peter · committed by David Peter · parent f342e1f · Browse files · 3 files+88 added−40 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+88 added−40 removed

  • other:+88 added−40 removed

3 files+88 added−40 removed

modified:src/benchmark/measurement.rs+11 added-32 removed
62 unmodified lines
63 pub fn push(&mut self, measurement: Measurement) {64 self.measurements.push(measurement);65 }6667 pub fn wall_clock_times(&self) -> Vec<Time> {68 self.measurements69 .iter()70 .map(|m| m.time_wall_clock)71 .collect()67 pub fn wall_clock_times(&self) -> impl Iterator<Item = Time> + '_ {68 self.measurements.iter().map(|m| m.time_wall_clock)69 }7071 /// The average wall clock time72 pub fn time_wall_clock_mean(&self) -> Time {76 mean(&self.wall_clock_times())73 mean(self.wall_clock_times())74 }7576 /// The standard deviation of all wall clock times. Not available if only one run has been performed77 pub fn stddev(&self) -> Option<Time> {81 let times = self.wall_clock_times();78 let times: Vec<_> = self.wall_clock_times().collect(); // TODO: Avoid collecting7980 if times.len() < 2 {81 None82 } else {
2 unmodified lines
85 }8687 /// The median wall clock time88 pub fn median(&self) -> Time {92 median(&self.wall_clock_times())89 median(&self.wall_clock_times().collect::<Vec<_>>())90 }9192 /// The minimum wall clock time93 pub fn min(&self) -> Time {97 min(&self.wall_clock_times())94 min(self.wall_clock_times())95 }9697 /// The maximum wall clock time98 pub fn max(&self) -> Time {102 max(&self.wall_clock_times())99 max(self.wall_clock_times())100 }101102 /// Compute modified Z-scores for the wall clock times103 pub fn modified_zscores(&self) -> Vec<f64> {107 modified_zscores(&self.wall_clock_times())104 modified_zscores(&self.wall_clock_times().collect::<Vec<_>>())105 }106107 /// The average user time108 pub fn time_user_mean(&self) -> Time {112 mean(113 &self114 .measurements115 .iter()116 .map(|m| m.time_user)117 .collect::<Vec<_>>(),118 )109 mean(self.measurements.iter().map(|m| m.time_user))110 }111112 /// The average system time113 pub fn time_system_mean(&self) -> Time {123 mean(124 &self125 .measurements126 .iter()127 .map(|m| m.time_system)128 .collect::<Vec<_>>(),129 )114 mean(self.measurements.iter().map(|m| m.time_system))115 }116117 pub fn peak_memory_usage_mean(&self) -> Information {133 mean(134 &self135 .measurements136 .iter()137 .map(|m| m.peak_memory_usage)138 .collect::<Vec<_>>(),139 )118 mean(self.measurements.iter().map(|m| m.peak_memory_usage))119 }120121 pub fn peak_memory_usage_mean(&self) -> Information {122 mean(self.measurements.iter().map(|m| m.peak_memory_usage))
2 unmodified lines
modified:src/benchmark/mod.rs+3 added-4 removed
20 unmodified lines
21 finish_initial_measurement, get_progress_bar, start_initial_measurement,22};23use crate::output::warnings::{OutlierWarningOptions, Warnings};24use crate::parameter::ParameterNameAndValue;25use crate::quantity::{self, const_time_from_seconds, Time, Quantity};25use crate::quantity::{self, const_time_from_seconds, Quantity, Time};26use benchmark_result::BenchmarkResult;2728use anyhow::{anyhow, Result};29use colored::*;
390 unmodified lines
420 // Check execution time421 if matches!(self.options.executor_kind, ExecutorKind::Shell(_))422 && measurements423 .wall_clock_times()424 .iter()425 .any(|&t| t < MIN_EXECUTION_TIME)424 .any(|t| t < MIN_EXECUTION_TIME)425 {426 warnings.push(Warnings::FastExecutionTime);427 }428
17 unmodified lines
446 };447448 if scores[0] > OUTLIER_THRESHOLD {449 warnings.push(Warnings::SlowInitialRun(451 measurements.wall_clock_times()[0],450 measurements.wall_clock_times().next().unwrap(),451 outlier_warning_options,452 ));453 } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {454 warnings.push(Warnings::OutliersDetected(outlier_warning_options));
37 unmodified lines
modified:src/quantity/mod.rs+74 added-4 removed
1use core::f64;2use std::marker::PhantomData;3use std::ops::AddAssign;4use std::ops::Div;56use serde::ser::SerializeStruct;7use serde::Serializer;89use uom::num_traits;10use uom::si;11pub use uom::si::information::{byte, gibibyte, kibibyte, mebibyte, tebibyte};12pub use uom::si::ratio::ratio;13pub use uom::si::time::{hour, microsecond, millisecond, minute, nanosecond, second};
161 unmodified lines
175 }176 };177}178176quantity_fn!(mean, values, statistical::mean(&values));179/// A max function that assumes no NaNs and at least one element180pub fn max<V: PartialOrd>(values: impl IntoIterator<Item = V>) -> V {181 values182 .into_iter()183 .max_by(|a, b| a.partial_cmp(b).expect("No NaN values"))184 .expect("'max' requires at least one element")185}186187/// A min function that assumes no NaNs and at least one element188pub fn min<V: PartialOrd>(values: impl IntoIterator<Item = V>) -> V {189 values190 .into_iter()191 .min_by(|a, b| a.partial_cmp(b).expect("No NaN values"))192 .expect("'min' requires at least one element")193}194195/// A mean function that assumes at least one element196pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q197where198 Q: AddAssign + num_traits::Zero + Div<Ratio, Output = P>,199 P: Into<Q>,200{201 let mut sum = Q::zero();202 let mut count = 0;203 for value in values {204 sum += value;205 count += 1;206 }207208 let count = Ratio::new::<ratio>(count as f64);209 (sum / count).into()210}211212quantity_fn!(median, values, statistical::median(&values));178quantity_fn!(min, values, crate::util::min_max::min(&values));179quantity_fn!(max, values, crate::util::min_max::max(&values));213quantity_fn!(standard_deviation, values, {214 let mean_value = statistical::mean(&values);215 statistical::standard_deviation(&values, Some(mean_value))216});
3 unmodified lines
220 crate::outlier_detection::modified_zscores(&values)221}222223#[test]224fn test_max() {225 assert_eq!(1.0, max([1.0]));226 assert_eq!(-1.0, max([-1.0]));227 assert_eq!(-1.0, max([-2.0, -1.0]));228 assert_eq!(1.0, max([-1.0, 1.0]));229 assert_eq!(1.0, max([-1.0, 1.0, 0.0]));230}231232#[test]233fn test_time() {234 let time = Time::new::<millisecond>(123.4);235 assert_eq!(time.get::<millisecond>(), 123.4);236
38 unmodified lines
275 let values = vec![276 Time::new::<millisecond>(123.4),277 Time::new::<millisecond>(234.5),278 ];237 let result = mean(&values);279 let result = mean(values.into_iter());280 assert_eq!(result.format(TimeUnit::MilliSecond), "178.9 ms");281}282283#[test]
28 unmodified lines
312313 let out = Time::new::<second>(1.3).format(TimeUnit::MicroSecond);314 assert_eq!("1300000.0 µs", out);315}316317#[test]318fn statistics() {319 let values = vec![320 Time::new::<second>(1.0),321 Time::new::<second>(2.0),322 Time::new::<second>(3.0),323 ];324325 assert_eq!(326 mean(values.iter().copied()).format(TimeUnit::Second),327 "2.000 s"328 );329 assert_eq!(median(&values).format(TimeUnit::Second), "2.000 s");330 assert_eq!(min(&values).format(TimeUnit::Second), "1.000 s");331 assert_eq!(max(&values).format(TimeUnit::Second), "3.000 s");332 assert_eq!(333 standard_deviation(&values).format(TimeUnit::Second),334 "1.000 s"335 );336337 let values = vec![338 Information::new::<byte>(1.0),339 Information::new::<byte>(2.0),340 Information::new::<byte>(3.0),341 ];342 mean(values.iter().copied()).format(InformationUnit::Byte);343}