Switch to unit-safe quantities
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 914d5cb · Browse files · 15 files·+384 added−272 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+384 added−272 removed
- other:+384 added−272 removed
Provenance
- Commit
f9aa299- Tree
be2376a- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
David Peter <mail@david-peter.de>- Parent
914d5cb
15 files changed+384 added−272 removed
modified:src/benchmark/benchmark_result.rs+1 added-1 removed
1 use std::collections::BTreeMap;2 3 use serde::Serialize;4 5-use crate::{benchmark::measurement::Measurements, util::units::Second};5+use crate::benchmark::{measurement::Measurements, quantity::Second};6 7 /// Parameter value and whether it was used in the command line template8 #[derive(Debug, Default, Clone, Serialize, PartialEq)]9 pub struct Parameter {54 unmodified linesmodified:src/benchmark/executor.rs+25 added-16 removed
1 #[cfg(windows)]2 use std::os::windows::process::CommandExt;3 use std::process::ExitStatus;4 5+use crate::benchmark::quantity::mean;6+use crate::benchmark::quantity::Byte;7+use crate::benchmark::quantity::Second;8 use crate::command::Command;9 use crate::options::{10 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,11 };151 unmodified lines163 fn calibrate(&mut self) -> Result<()> {164 Ok(())165 }166 164- fn time_overhead(&self) -> Time {165- Time::zero()167+ fn time_overhead(&self) -> Second {168+ Second::zero()169 }170 }171 172 pub struct ShellExecutor<'a> {41 unmodified lines214 &command.get_command_line(),215 )?;216 217 // Subtract shell spawning time218+ fn ensure_non_negative(time: Second) -> Second {219+ if time < Second::zero() {220+ Second::zero()221+ } else {222+ time223+ }224+ }225+226 if let Some(spawning_time) = self.shell_spawning_time {227 result.time_wall_clock =217- (result.time_wall_clock - spawning_time.time_wall_clock).max(0.0);218- result.time_user = (result.time_user - spawning_time.time_user).max(0.0);219- result.time_system = (result.time_system - spawning_time.time_system).max(0.0);228+ ensure_non_negative(result.time_wall_clock - spawning_time.time_wall_clock);229+ result.time_user = ensure_non_negative(result.time_user - spawning_time.time_user);230+ result.time_system =231+ ensure_non_negative(result.time_system - spawning_time.time_system);232 }233 234 Ok((235 TimingResult {18 unmodified lines254 } else {255 None256 };257 246- let mut times_wall_clock: Vec<Second> = vec![];258+ let mut times_wall_clock: Vec<Second> = vec![]; // TODO259 let mut times_user: Vec<Second> = vec![];260 let mut times_system: Vec<Second> = vec![];261 262 for _ in 0..COUNT {37 unmodified lines300 self.shell_spawning_time = Some(TimingResult {301 time_wall_clock: mean(×_wall_clock),302 time_user: mean(×_user),303 time_system: mean(×_system),292- memory_usage_byte: 0,304+ memory_usage_byte: Byte::new(0),305 });306 307 Ok(())308 }14 unmodified lines323 }324 325 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {326 assert!(sleep_command.as_ref().starts_with("sleep "));315- Time::new::<second>(327+ Second::new(328 sleep_command329 .as_ref()330 .trim_start_matches("sleep ")331 .parse::<f64>()24 unmodified lines356 357 Ok((358 TimingResult {359 time_wall_clock: Self::extract_time(command.get_command_line()),348- time_user: 0.0,349- time_system: 0.0,350- memory_usage_byte: 0,360+ time_user: Second::zero(),361+ time_system: Second::zero(),362+ memory_usage_byte: Byte::new(0),363 },364 status,365 ))366 }3 unmodified lines370 }371 372 fn time_overhead(&self) -> Time {373 match &self.shell {362- None => Time::zero(),374+ None => Second::zero(),375 Some(shell) => Self::extract_time(shell),376 }377 }378 }379 380 #[test]381 fn test_mock_executor_extract_time() {370- assert_eq!(371- MockExecutor::extract_time("sleep 0.1"),372- Time::new::<second>(0.1)373- );382+ assert_eq!(MockExecutor::extract_time("sleep 0.1"), Second::new(0.1));383 }modified:src/benchmark/measurement.rs+14 added-14 removed
1 use serde::Serialize;2 3-use statistical::{mean, median, standard_deviation};3+use crate::benchmark::quantity::{max, mean, median, min, standard_deviation, Byte, Second};4+use crate::outlier_detection::modified_zscores;5 5-use crate::util::units::Second;6-use crate::{7- outlier_detection::modified_zscores,8- util::min_max::{max, min},9-};10-6 /// Performance metric measurements and exit code for a single run7 #[derive(Debug, Clone, Serialize, PartialEq)]8 pub struct Measurement {9 /// Elapsed wall clock time (real time)4 unmodified lines14 15 /// Time spent in kernel mode16 pub system_time: Second,17 23- /// Maximum memory usage of the process, in bytes24- pub memory_usage_byte: u64,18+ /// Maximum memory usage of the process19+ pub memory_usage_byte: Byte,20 21 /// Exit codes of the process22 pub exit_code: Option<i32>,23 }35 unmodified lines59 /// The standard deviation of all wall clock times. Not available if only one run has been performed60 pub fn stddev(&self) -> Option<Second> {61 let times = self.wall_clock_times();62 68- let t_mean = mean(×);69- if times.len() > 1 {63+ if times.len() < 2 {70- Some(standard_deviation(×, Some(t_mean)))71- } else {64 None65+ } else {66+ Some(standard_deviation(×))67 }68 }69 70 /// The median wall clock time33 unmodified lines104 )105 }106 107 pub fn modified_zscores(&self) -> Vec<f64> {114- modified_zscores(&self.wall_clock_times())108+ modified_zscores(109+ &self110+ .wall_clock_times()111+ .iter()112+ .map(|t| t.value_in::<Second>()) // TODO113+ .collect::<Vec<_>>(),114+ )115 }116 117 pub fn peak_memory_usage_mean(&self) -> Information {118 mean(self.measurements.iter().map(|m| m.peak_memory_usage))2 unmodified linesmodified:src/benchmark/mod.rs+5 added-5 removed
10 unmodified lines11 12 use crate::benchmark::benchmark_result::Parameter;13 use crate::benchmark::executor::BenchmarkIteration;14 use crate::benchmark::measurement::{Measurement, Measurements};15+use crate::benchmark::quantity::{MilliSecond, Second};16 use crate::command::Command;17 use crate::options::{18 CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,19 };6 unmodified lines26 use crate::output::warnings::{OutlierWarningOptions, Warnings};27 use crate::parameter::ParameterNameAndValue;28 use crate::quantity::{byte, const_time_from_seconds, ratio, second, FormatQuantity, Time, Zero};29 use crate::util::exit_code::extract_exit_code;29-use crate::util::units::Second;30 use benchmark_result::BenchmarkResult;31 use measurement::{Measurement, Measurements};32 33 use anyhow::{anyhow, Result};1 unmodified line35 36 use self::executor::Executor;37 38 /// Threshold for warning about fast execution time39-pub const MIN_EXECUTION_TIME: Time = const_time_from_seconds(5e-3);39+pub const MIN_EXECUTION_TIME: MilliSecond = MilliSecond::new(5.);40 41 pub struct Benchmark<'a> {42 number: usize,43 command: &'a Command<'a>,220 unmodified lines264 None265 };266 267 let preparation_result = run_preparation_command()?;268- let preparation_overhead = preparation_result.map_or(0.0, |res| {268+ let preparation_overhead = preparation_result.map_or(Second::zero(), |res| {269 res.time_wall_clock + self.executor.time_overhead()270 });271 272 // Initial timing run20 unmodified lines293 );294 }295 296 let conclusion_result = run_conclusion_command()?;297- let conclusion_overhead = conclusion_result.map_or(0.0, |res| {297+ let conclusion_overhead = conclusion_result.map_or(Second::zero(), |res| {298 res.time_wall_clock + self.executor.time_overhead()299 });300 301 // Determine number of benchmark runs131 unmodified lines433 if matches!(self.options.executor_kind, ExecutorKind::Shell(_))434 && measurements435 .wall_clock_times()436 .iter()437- .any(|&t| t < MIN_EXECUTION_TIME)437+ .any(|&t| t < MIN_EXECUTION_TIME.convert_to::<Second>())438 {439 warnings.push(Warnings::FastExecutionTime);440 }441 63 unmodified linesmodified:src/benchmark/quantity.rs+169 added-67 removed
1-use std::fmt::{self, Display, Formatter};1+use std::{2+ fmt::{self, Display, Formatter},3+ ops::{Add, Div, Sub},4+};5 6 use serde::Serialize;7 5-#[derive(Debug, Clone, Serialize, PartialEq)]6-enum MetricPrefix {7- Nano,8- Micro,9- Milli,10- None,8+pub trait IsQuantity {9+ type Value;10+11+ const IS_TIME: bool;12+ const METRIC_PREFIX_TIME: i32;13+ const IS_INFORMATION: bool;14+ const BINARY_PREFIX_INFORMATION: i32;15+16+ fn unsafe_from(value: Self::Value) -> Self;17 }18 13-impl Display for MetricPrefix {14- fn fmt(&self, f: &mut Formatter) -> fmt::Result {15- match self {16- MetricPrefix::Nano => write!(f, "n"),17- MetricPrefix::Micro => write!(f, "µ"),18- MetricPrefix::Milli => write!(f, "m"),19- MetricPrefix::None => Ok(()),20- }19+#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq, PartialOrd)] // TODO: check partialord20+pub struct Quantity<21+ Value,22+ const IS_TIME: bool,23+ const METRIC_PREFIX_TIME: i32,24+ const IS_INFORMATION: bool,25+ const BINARY_PREFIX_INFORMATION: i32,26+>(Value);27+28+impl<29+ Value,30+ const IS_TIME: bool,31+ const METRIC_PREFIX_TIME: i32,32+ const IS_INFORMATION: bool,33+ const BINARY_PREFIX_INFORMATION: i32,34+ > IsQuantity35+ for Quantity<Value, IS_TIME, METRIC_PREFIX_TIME, IS_INFORMATION, BINARY_PREFIX_INFORMATION>36+{37+ type Value = Value;38+ const IS_TIME: bool = IS_TIME;39+ const METRIC_PREFIX_TIME: i32 = METRIC_PREFIX_TIME;40+ const IS_INFORMATION: bool = IS_INFORMATION;41+ const BINARY_PREFIX_INFORMATION: i32 = BINARY_PREFIX_INFORMATION;42+43+ fn unsafe_from(value: Self::Value) -> Self {44+ Self(value)45 }46 }47 24-#[derive(Debug, Clone, Serialize, PartialEq)]25-enum BinaryPrefix {26- None,27- Kibi,28- Mebi,29- Gibi,30- Tebi,31-}48+type Time<const PREFIX: i32> = Quantity<f64, true, PREFIX, false, 0>;49+type Information<const PREFIX: i32> = Quantity<u64, false, 0, true, PREFIX>;50 33-impl Display for BinaryPrefix {34- fn fmt(&self, f: &mut Formatter) -> fmt::Result {35- match self {36- BinaryPrefix::None => Ok(()),37- BinaryPrefix::Kibi => write!(f, "Ki"),38- BinaryPrefix::Mebi => write!(f, "Mi"),39- BinaryPrefix::Gibi => write!(f, "Gi"),40- BinaryPrefix::Tebi => write!(f, "Ti"),51+pub type Second = Time<0>;52+pub type MilliSecond = Time<-3>;53+pub type MicroSecond = Time<-6>;54+55+pub type Byte = Information<0>;56+pub type KibiByte = Information<10>;57+pub type MebiByte = Information<20>;58+pub type GibiByte = Information<30>;59+pub type TebiByte = Information<40>;60+61+impl<62+ Value: Copy + Default,63+ const IS_TIME: bool,64+ const METRIC_PREFIX_TIME: i32,65+ const IS_INFORMATION: bool,66+ const BINARY_PREFIX_INFORMATION: i32,67+ > Quantity<Value, IS_TIME, METRIC_PREFIX_TIME, IS_INFORMATION, BINARY_PREFIX_INFORMATION>68+{69+ pub const fn new(value: Value) -> Self {70+ Self(value)71+ }72+73+ pub fn zero() -> Self {74+ Self::new(Value::default())75+ }76+77+ pub fn value_in<TargetUnit: IsQuantity>(&self) -> Value {78+ const {79+ assert!(IS_TIME == TargetUnit::IS_TIME);80+ assert!(METRIC_PREFIX_TIME == TargetUnit::METRIC_PREFIX_TIME);81+ assert!(IS_INFORMATION == TargetUnit::IS_INFORMATION);82+ assert!(BINARY_PREFIX_INFORMATION == TargetUnit::BINARY_PREFIX_INFORMATION);83 }84+85+ self.086 }87 }88 45-#[derive(Debug, Clone, Serialize, PartialEq)]46-pub enum Unit {47- Second(MetricPrefix),48- Byte(BinaryPrefix),89+impl<const METRIC_PREFIX_TIME: i32> Time<METRIC_PREFIX_TIME> {90+ pub fn convert_to<TargetUnit: IsQuantity<Value = f64>>(&self) -> TargetUnit {91+ let factor = 10_f64.powi(METRIC_PREFIX_TIME - TargetUnit::METRIC_PREFIX_TIME);92+93+ TargetUnit::unsafe_from(self.0 * factor)94+ }95 }96 51-pub const SECOND: Unit = Unit::Second(MetricPrefix::None);52-pub const MILLISECOND: Unit = Unit::Second(MetricPrefix::Milli);53-pub const MICROSECOND: Unit = Unit::Second(MetricPrefix::Micro);54-pub const BYTE: Unit = Unit::Byte(BinaryPrefix::None);97+impl<const METRIC_PREFIX_TIME: i32> Add<Time<METRIC_PREFIX_TIME>> for Time<METRIC_PREFIX_TIME> {98+ type Output = Time<METRIC_PREFIX_TIME>;99 56-impl Display for Unit {57- fn fmt(&self, f: &mut Formatter) -> fmt::Result {58- match self {59- Unit::Second(prefix) => write!(f, "{prefix}s",),60- Unit::Byte(prefix) => write!(f, "{prefix}B"),61- }100+ fn add(self, rhs: Time<METRIC_PREFIX_TIME>) -> Self::Output {101+ Time::new(self.0 + rhs.0)102 }103 }104 65-#[derive(Debug, Clone, Serialize, PartialEq)]66-pub struct Quantity<Value> {67- value: Value,68- unit: Unit,105+impl<const METRIC_PREFIX_TIME: i32> Sub<Time<METRIC_PREFIX_TIME>> for Time<METRIC_PREFIX_TIME> {106+ type Output = Time<METRIC_PREFIX_TIME>;107+108+ fn sub(self, rhs: Time<METRIC_PREFIX_TIME>) -> Self::Output {109+ Time::new(self.0 - rhs.0)110+ }111 }112 71-impl<Value> Quantity<Value> {72- pub fn new(value: Value, unit: Unit) -> Self {73- Self { value, unit }113+impl<const METRIC_PREFIX_TIME: i32> Div<Time<METRIC_PREFIX_TIME>> for Time<METRIC_PREFIX_TIME> {114+ type Output = f64;115+116+ fn div(self, rhs: Time<METRIC_PREFIX_TIME>) -> Self::Output {117+ self.0 / rhs.0118 }119 }120 77-impl<Value: Display> Display for Quantity<Value> {121+impl<const METRIC_PREFIX_TIME: i32> Display for Time<METRIC_PREFIX_TIME> {122 fn fmt(&self, f: &mut Formatter) -> fmt::Result {79- write!(f, "{} {}", self.value, self.unit)123+ let prefix = match METRIC_PREFIX_TIME {124+ -6 => "µ",125+ -3 => "m",126+ 0 => "s",127+ _ => unreachable!(),128+ };129+ write!(f, "{} {}s", self.0, prefix)130 }131 }132 83-pub fn mean(values: &[Quantity<f64>]) -> Quantity<f64> {84- statistical::mean(values).unwrap()133+impl<const BINARY_PREFIX_INFORMATION: i32> Display for Information<BINARY_PREFIX_INFORMATION> {134+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {135+ let prefix = match BINARY_PREFIX_INFORMATION {136+ 0 => "",137+ 10 => "Ki",138+ 20 => "Mi",139+ 30 => "Gi",140+ 40 => "Ti",141+ _ => unreachable!(),142+ };143+ write!(f, "{} {}B", self.0, prefix)144+ }145 }146 87-pub type Time = Quantity<f64>;88-pub type Memory = Quantity<u64>;147+macro_rules! quantity_fn {148+ ($name:ident, $unwrapped_values:ident, $body:expr) => {149+ pub fn $name<150+ const IS_TIME: bool,151+ const METRIC_PREFIX_TIME: i32,152+ const IS_INFORMATION: bool,153+ const BINARY_PREFIX_INFORMATION: i32,154+ >(155+ values: &[Quantity<156+ f64,157+ IS_TIME,158+ METRIC_PREFIX_TIME,159+ IS_INFORMATION,160+ BINARY_PREFIX_INFORMATION,161+ >],162+ ) -> Quantity<f64, IS_TIME, METRIC_PREFIX_TIME, IS_INFORMATION, BINARY_PREFIX_INFORMATION> {163+ let $unwrapped_values: Vec<f64> = values.iter().map(|v| v.0).collect();164+ let result_value = $body;165+ Quantity::new(result_value)166+ }167+ };168+}169 170+quantity_fn!(mean, values, statistical::mean(&values));171+quantity_fn!(median, values, statistical::median(&values));172+quantity_fn!(min, values, crate::util::min_max::min(&values));173+quantity_fn!(max, values, crate::util::min_max::max(&values));174+quantity_fn!(standard_deviation, values, {175+ let mean_value = statistical::mean(&values);176+ statistical::standard_deviation(&values, Some(mean_value))177+});178+179 #[test]91-fn basic() {92- let time = Time {93- value: 123.4,94- unit: Unit::Second(MetricPrefix::Milli),95- };180+fn test_quantity() {181+ let time = MilliSecond::new(123.4);182+ assert_eq!(time.value_in::<MilliSecond>(), 123.4);183+184+ let time_s = time.convert_to::<Second>();185+ approx::assert_relative_eq!(time_s.value_in::<Second>(), 0.1234);186+187+ let time_us = time.convert_to::<MicroSecond>();188+ approx::assert_relative_eq!(time_us.value_in::<MicroSecond>(), 123400.0);189+}190+191+#[test]192+fn test_format() {193+ let time = MilliSecond::new(123.4);194 assert_eq!(time.to_string(), "123.4 ms");195 98- let peak_memory_usage = Memory {99- value: 8,100- unit: Unit::Byte(BinaryPrefix::Kibi),101- };196+ let peak_memory_usage = KibiByte::new(8);197 assert_eq!(peak_memory_usage.to_string(), "8 KiB");198 }199+200+#[test]201+fn test_mean() {202+ let values = vec![MilliSecond::new(123.4), MilliSecond::new(234.5)];203+ let result = mean(&values);204+ assert_eq!(result.to_string(), "178.95 ms");205+}modified:src/benchmark/relative_speed.rs+14 added-13 removed
1 use std::cmp::Ordering;2 3 use super::benchmark_result::BenchmarkResult;4-use crate::{5- options::SortOrder,6- quantity::{self, Ratio, Time, Zero},7-};4+use crate::{benchmark::quantity::Second, options::SortOrder};5 6 #[derive(Debug)]7 pub struct BenchmarkResultWithRelativeSpeed<'a> {8 pub result: &'a BenchmarkResult,42 unmodified lines51 // Separate benchmarks can have identical names and measurements.52 let is_reference = std::ptr::eq(result, reference);53 let relative_ordering = compare_mean_time(result, reference);54 58- if result.mean_wall_clock_time() == Time::zero()59- || reference.mean_wall_clock_time() == Time::zero()55+ if result.mean_wall_clock_time() == Second::zero()56+ || reference.mean_wall_clock_time() == Second::zero()57 {58 return BenchmarkResultWithRelativeSpeed {59 result,60 relative_speed: if is_reference { 1.0 } else { f64::INFINITY },52 unmodified lines113 results: &'a [BenchmarkResult],114 reference: &'a BenchmarkResult,115 sort_order: SortOrder,116 ) -> Option<Vec<BenchmarkResultWithRelativeSpeed<'a>>> {120- if fastest_of(results).mean_wall_clock_time() == 0.0 || reference.mean_wall_clock_time() == 0.0117+ if fastest_of(results).mean_wall_clock_time() == Second::zero()118+ || reference.mean_wall_clock_time() == Second::zero()119 {120 return None;121 }122 5 unmodified lines128 sort_order: SortOrder,129 ) -> Option<Vec<BenchmarkResultWithRelativeSpeed<'_>>> {130 let fastest = fastest_of(results);131 134- if fastest.mean_wall_clock_time() == 0.0 {132+ if fastest.mean_wall_clock_time() == Second::zero() {133 return None;134 }135 136 Some(compute_relative_speeds(results, fastest, sort_order))12 unmodified lines149 #[cfg(test)]150 fn create_result(name: &str, mean: f64) -> BenchmarkResult {151 use std::collections::BTreeMap;152 155- use crate::benchmark::measurement::{Measurement, Measurements};153+ use crate::benchmark::{154+ measurement::{Measurement, Measurements},155+ quantity::Byte,156+ };157 158 BenchmarkResult {159 command: name.into(),160 measurements: Measurements {161 measurements: vec![Measurement {161- wall_clock_time: mean,162- user_time: mean,163- system_time: 0.,164- memory_usage_byte: 1024,162+ wall_clock_time: Second::new(mean),163+ user_time: Second::new(mean),164+ system_time: Second::zero(),165+ memory_usage_byte: Byte::new(1024),166 exit_code: Some(0),167 }],168 },169 parameters: BTreeMap::new(),67 unmodified linesmodified:src/export/csv.rs+28 added-37 removed
2 unmodified lines3 use csv::WriterBuilder;4 5 use super::Exporter;6 use crate::benchmark::benchmark_result::BenchmarkResult;7+use crate::benchmark::quantity::Second;8 use crate::options::SortOrder;9 use crate::quantity::{FormatQuantity, TimeUnit};10 11 use anyhow::Result;33 unmodified lines45 for res in results {46 let mut fields = vec![Cow::Borrowed(res.command.as_bytes())];47 for f in &[48 res.mean_wall_clock_time(),48- res.measurements.stddev().unwrap_or(0.0),49+ res.measurements.stddev().unwrap_or_default(),50 res.measurements.median(),51 res.measurements.user_mean(),52 res.measurements.system_mean(),53 res.measurements.min(),54 res.measurements.max(),55 ] {55- fields.push(Cow::Owned(56- f.format_with_precision(CSV_UNIT, CSV_PRECISION)57- .into_bytes(),58- ))56+ fields.push(Cow::Owned(f.value_in::<Second>().to_string().into_bytes()))57 }58 for v in res.parameters.values() {59 fields.push(Cow::Borrowed(v.value.as_bytes()))60 }3 unmodified lines64 Ok(writer.into_inner()?)65 }66 }67 70-#[cfg(test)]71-use crate::benchmark::benchmark_result::Parameter;72-73-#[cfg(test)]74-use crate::benchmark::measurement::{Measurement, Measurements};75-68 #[test]69 fn test_csv() {70 use crate::benchmark::benchmark_result::Parameter;71 use crate::benchmark::measurement::{Measurement, Measurements};80- use crate::quantity::{byte, second, Information, Time, Zero};72+ use crate::benchmark::quantity::{Byte, Second};73 74 use std::collections::BTreeMap;83- use std::process::ExitStatus;75 76 let exporter = CsvExporter::default();77 78 let results = vec![79 BenchmarkResult {80 command: String::from("command_a"),81 measurements: Measurements::new(vec![82 Measurement {92- wall_clock_time: 7.0,93- user_time: 7.0,94- system_time: 0.0,95- memory_usage_byte: 1024,83+ wall_clock_time: Second::new(7.0),84+ user_time: Second::new(7.0),85+ system_time: Second::zero(),86+ memory_usage_byte: Byte::new(1024),87 exit_code: Some(0),88 },89 Measurement {99- wall_clock_time: 8.0,100- user_time: 8.0,101- system_time: 0.0,102- memory_usage_byte: 1024,90+ wall_clock_time: Second::new(8.0),91+ user_time: Second::new(8.0),92+ system_time: Second::zero(),93+ memory_usage_byte: Byte::new(1024),94 exit_code: Some(0),95 },96 Measurement {106- wall_clock_time: 12.0,107- user_time: 12.0,108- system_time: 0.0,109- memory_usage_byte: 1024,97+ wall_clock_time: Second::new(12.0),98+ user_time: Second::new(12.0),99+ system_time: Second::zero(),100+ memory_usage_byte: Byte::new(1024),101 exit_code: Some(0),102 },103 ]),104 parameters: {18 unmodified lines123 BenchmarkResult {124 command: String::from("command_b"),125 measurements: Measurements::new(vec![126 Measurement {136- wall_clock_time: 17.0,137- user_time: 17.0,138- system_time: 0.0,139- memory_usage_byte: 1024,127+ wall_clock_time: Second::new(17.0),128+ user_time: Second::new(17.0),129+ system_time: Second::zero(),130+ memory_usage_byte: Byte::new(1024),131 exit_code: Some(0),132 },133 Measurement {143- wall_clock_time: 18.0,144- user_time: 18.0,145- system_time: 0.0,146- memory_usage_byte: 1024,134+ wall_clock_time: Second::new(18.0),135+ user_time: Second::new(18.0),136+ system_time: Second::zero(),137+ memory_usage_byte: Byte::new(1024),138 exit_code: Some(0),139 },140 Measurement {150- wall_clock_time: 19.0,151- user_time: 19.0,152- system_time: 0.0,153- memory_usage_byte: 1024,141+ wall_clock_time: Second::new(19.0),142+ user_time: Second::new(19.0),143+ system_time: Second::zero(),144+ memory_usage_byte: Byte::new(1024),145 exit_code: Some(0),146 },147 ]),148 parameters: {33 unmodified linesmodified:src/export/tests.rs+97 added-96 removed
1 use super::Exporter;2 use crate::benchmark::benchmark_result::BenchmarkResult;3 use crate::benchmark::measurement::{Measurement, Measurements};4+use crate::benchmark::quantity::{Byte, Second};5 use crate::export::asciidoc::AsciidocExporter;6 use crate::export::orgmode::OrgmodeExporter;7 use crate::quantity::{byte, second, Information, Time, TimeUnit, Zero};8 use crate::{export::markdown::MarkdownExporter, options::SortOrder};21 unmodified lines30 BenchmarkResult {31 command: String::from("sleep 0.1"),32 measurements: Measurements::new(vec![33 Measurement {33- wall_clock_time: 0.09,34- user_time: 0.09,35- system_time: 0.,36- memory_usage_byte: 1024,34+ wall_clock_time: Second::new(0.09),35+ user_time: Second::new(0.09),36+ system_time: Second::zero(),37+ memory_usage_byte: Byte::new(1024),38 exit_code: Some(0),39 },40 Measurement {40- wall_clock_time: 0.10,41- user_time: 0.10,42- system_time: 0.,43- memory_usage_byte: 1024,41+ wall_clock_time: Second::new(0.10),42+ user_time: Second::new(0.10),43+ system_time: Second::zero(),44+ memory_usage_byte: Byte::new(1024),45 exit_code: Some(0),46 },47 Measurement {47- wall_clock_time: 0.14,48- user_time: 0.14,49- system_time: 0.,50- memory_usage_byte: 1024,48+ wall_clock_time: Second::new(0.14),49+ user_time: Second::new(0.14),50+ system_time: Second::zero(),51+ memory_usage_byte: Byte::new(1024),52 exit_code: Some(0),53 },54 ]),55 parameters: BTreeMap::new(),1 unmodified line57 BenchmarkResult {58 command: String::from("sleep 2"),59 measurements: Measurements::new(vec![60 Measurement {60- wall_clock_time: 2.0,61- user_time: 2.0,62- system_time: 0.,63- memory_usage_byte: 1024,61+ wall_clock_time: Second::new(2.0),62+ user_time: Second::new(2.0),63+ system_time: Second::zero(),64+ memory_usage_byte: Byte::new(1024),65 exit_code: Some(0),66 },67 Measurement {67- wall_clock_time: 3.0,68- user_time: 3.0,69- system_time: 0.,70- memory_usage_byte: 1024,68+ wall_clock_time: Second::new(3.0),69+ user_time: Second::new(3.0),70+ system_time: Second::zero(),71+ memory_usage_byte: Byte::new(1024),72 exit_code: Some(0),73 },74 Measurement {74- wall_clock_time: 4.0,75- user_time: 4.0,76- system_time: 0.,77- memory_usage_byte: 1024,75+ wall_clock_time: Second::new(4.0),76+ user_time: Second::new(4.0),77+ system_time: Second::zero(),78+ memory_usage_byte: Byte::new(1024),79 exit_code: Some(0),80 },81 ]),82 parameters: BTreeMap::new(),46 unmodified lines129 BenchmarkResult {130 command: String::from("sleep 2"),131 measurements: Measurements::new(vec![132 Measurement {132- wall_clock_time: 2.1,133- user_time: 2.1,134- system_time: 0.,135- memory_usage_byte: 1024,133+ wall_clock_time: Second::new(2.1),134+ user_time: Second::new(2.1),135+ system_time: Second::zero(),136+ memory_usage_byte: Byte::new(1024),137 exit_code: Some(0),138 },139 Measurement {139- wall_clock_time: 2.2,140- user_time: 2.2,141- system_time: 0.,142- memory_usage_byte: 1024,140+ wall_clock_time: Second::new(2.2),141+ user_time: Second::new(2.2),142+ system_time: Second::zero(),143+ memory_usage_byte: Byte::new(1024),144 exit_code: Some(0),145 },146 Measurement {146- wall_clock_time: 2.3,147- user_time: 2.3,148- system_time: 0.,149- memory_usage_byte: 1024,147+ wall_clock_time: Second::new(2.3),148+ user_time: Second::new(2.3),149+ system_time: Second::zero(),150+ memory_usage_byte: Byte::new(1024),151 exit_code: Some(0),152 },153 ]),154 parameters: BTreeMap::new(),1 unmodified line156 BenchmarkResult {157 command: String::from("sleep 0.1"),158 measurements: Measurements::new(vec![159 Measurement {159- wall_clock_time: 0.1,160- user_time: 0.1,161- system_time: 0.,162- memory_usage_byte: 1024,160+ wall_clock_time: Second::new(0.1),161+ user_time: Second::new(0.1),162+ system_time: Second::zero(),163+ memory_usage_byte: Byte::new(1024),164 exit_code: Some(0),165 },166 Measurement {166- wall_clock_time: 0.2,167- user_time: 0.2,168- system_time: 0.,169- memory_usage_byte: 1024,167+ wall_clock_time: Second::new(0.2),168+ user_time: Second::new(0.2),169+ system_time: Second::zero(),170+ memory_usage_byte: Byte::new(1024),171 exit_code: Some(0),172 },173 Measurement {173- wall_clock_time: 0.3,174- user_time: 0.3,175- system_time: 0.,176- memory_usage_byte: 1024,174+ wall_clock_time: Second::new(0.3),175+ user_time: Second::new(0.3),176+ system_time: Second::zero(),177+ memory_usage_byte: Byte::new(1024),178 exit_code: Some(0),179 },180 ]),181 parameters: BTreeMap::new(),46 unmodified lines228 BenchmarkResult {229 command: String::from("sleep 2"),230 measurements: Measurements::new(vec![231 Measurement {231- wall_clock_time: 2.1,232- user_time: 2.1,233- system_time: 0.,234- memory_usage_byte: 1024,232+ wall_clock_time: Second::new(2.1),233+ user_time: Second::new(2.1),234+ system_time: Second::zero(),235+ memory_usage_byte: Byte::new(1024),236 exit_code: Some(0),237 },238 Measurement {238- wall_clock_time: 2.2,239- user_time: 2.2,240- system_time: 0.,241- memory_usage_byte: 1024,239+ wall_clock_time: Second::new(2.2),240+ user_time: Second::new(2.2),241+ system_time: Second::zero(),242+ memory_usage_byte: Byte::new(1024),243 exit_code: Some(0),244 },245 Measurement {245- wall_clock_time: 2.3,246- user_time: 2.3,247- system_time: 0.,248- memory_usage_byte: 1024,246+ wall_clock_time: Second::new(2.3),247+ user_time: Second::new(2.3),248+ system_time: Second::zero(),249+ memory_usage_byte: Byte::new(1024),250 exit_code: Some(0),251 },252 ]),253 parameters: BTreeMap::new(),1 unmodified line255 BenchmarkResult {256 command: String::from("sleep 0.1"),257 measurements: Measurements::new(vec![258 Measurement {258- wall_clock_time: 0.1,259- user_time: 0.1,260- system_time: 0.,261- memory_usage_byte: 1024,259+ wall_clock_time: Second::new(0.1),260+ user_time: Second::new(0.1),261+ system_time: Second::zero(),262+ memory_usage_byte: Byte::new(1024),263 exit_code: Some(0),264 },265 Measurement {265- wall_clock_time: 0.2,266- user_time: 0.2,267- system_time: 0.,268- memory_usage_byte: 1024,266+ wall_clock_time: Second::new(0.2),267+ user_time: Second::new(0.2),268+ system_time: Second::zero(),269+ memory_usage_byte: Byte::new(1024),270 exit_code: Some(0),271 },272 Measurement {272- wall_clock_time: 0.3,273- user_time: 0.3,274- system_time: 0.,275- memory_usage_byte: 1024,273+ wall_clock_time: Second::new(0.3),274+ user_time: Second::new(0.3),275+ system_time: Second::zero(),276+ memory_usage_byte: Byte::new(1024),277 exit_code: Some(0),278 },279 ]),280 parameters: BTreeMap::new(),45 unmodified lines326 BenchmarkResult {327 command: String::from("sleep 2"),328 measurements: Measurements::new(vec![329 Measurement {329- wall_clock_time: 2.01,330- user_time: 2.01,331- system_time: 0.,332- memory_usage_byte: 1024,330+ wall_clock_time: Second::new(2.01),331+ user_time: Second::new(2.01),332+ system_time: Second::zero(),333+ memory_usage_byte: Byte::new(1024),334 exit_code: Some(0),335 },336 Measurement {336- wall_clock_time: 2.02,337- user_time: 2.02,338- system_time: 0.,339- memory_usage_byte: 1024,337+ wall_clock_time: Second::new(2.02),338+ user_time: Second::new(2.02),339+ system_time: Second::zero(),340+ memory_usage_byte: Byte::new(1024),341 exit_code: Some(0),342 },343 Measurement {343- wall_clock_time: 2.03,344- user_time: 2.03,345- system_time: 0.,346- memory_usage_byte: 1024,344+ wall_clock_time: Second::new(2.03),345+ user_time: Second::new(2.03),346+ system_time: Second::zero(),347+ memory_usage_byte: Byte::new(1024),348 exit_code: Some(0),349 },350 ]),351 parameters: BTreeMap::new(),1 unmodified line353 BenchmarkResult {354 command: String::from("sleep 0.1"),355 measurements: Measurements::new(vec![356 Measurement {356- wall_clock_time: 0.11,357- user_time: 0.11,358- system_time: 0.,359- memory_usage_byte: 1024,357+ wall_clock_time: Second::new(0.11),358+ user_time: Second::new(0.11),359+ system_time: Second::zero(),360+ memory_usage_byte: Byte::new(1024),361 exit_code: Some(0),362 },363 Measurement {363- wall_clock_time: 0.12,364- user_time: 0.12,365- system_time: 0.,366- memory_usage_byte: 1024,364+ wall_clock_time: Second::new(0.12),365+ user_time: Second::new(0.12),366+ system_time: Second::zero(),367+ memory_usage_byte: Byte::new(1024),368 exit_code: Some(0),369 },370 Measurement {370- wall_clock_time: 0.13,371- user_time: 0.13,372- system_time: 0.,373- memory_usage_byte: 1024,371+ wall_clock_time: Second::new(0.13),372+ user_time: Second::new(0.13),373+ system_time: Second::zero(),374+ memory_usage_byte: Byte::new(1024),375 exit_code: Some(0),376 },377 ]),378 parameters: BTreeMap::new(),40 unmodified linesmodified:src/output/warnings.rs+3 added-3 removed
1 use std::fmt;2 3+use crate::benchmark::quantity::Second;4 use crate::benchmark::MIN_EXECUTION_TIME;4-use crate::quantity::{FormatQuantity, Time, TimeUnit};5+use crate::output::format::format_duration;6 7 pub struct OutlierWarningOptions {8 pub warmup_in_use: bool,9 pub prepare_in_use: bool,11 unmodified lines21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {22 match *self {23 Warnings::FastExecutionTime => write!(24 f,24- "Command took less than {} ms to complete. Note that the results might be \25+ "Command took less than {MIN_EXECUTION_TIME} to complete. Note that the results might be \26 inaccurate because hyperfine can not calibrate the shell startup time much \27 more precise than this limit. You can try to use the `-N`/`--shell=none` \28 option to disable the shell completely.",28- MIN_EXECUTION_TIME.format_with_precision(TimeUnit::MilliSecond, 0)29 ),30 Warnings::NonZeroExitCode => write!(f, "Ignoring non-zero exit code."),31 Warnings::SlowInitialRun(time_first_run, ref options) => write!(32 f,36 unmodified linesmodified:src/timer/mod.rs+2 added-2 removed
14 unmodified lines15 16 #[cfg(target_os = "windows")]17 use windows_sys::Win32::System::Threading::CREATE_SUSPENDED;18 19-use crate::benchmark::measurement::Measurement;19+use crate::benchmark::quantity::{Byte, Second};20 use wall_clock_timer::WallClockTimer;21 22 use std::io::Read;23 use std::process::{ChildStdout, Command};5 unmodified lines29 pub struct TimerResult {30 pub time_wall_clock: Second,31 pub time_user: Second,32 pub time_system: Second,33- pub memory_usage_byte: u64,33+ pub memory_usage_byte: Byte,34 /// The exit status of the process35 pub status: ExitStatus,36 }37 69 unmodified linesmodified:src/timer/unix_timer.rs+8 added-8 removed
6 unmodified lines7 use std::process::{Child, ExitStatus};8 9 use anyhow::Result;10 11-use crate::util::units::Second;11+use crate::benchmark::quantity::{Byte, Second};12 13 #[derive(Debug, Copy, Clone)]14 struct ResourceUsage {15 /// Total amount of time spent executing in user mode16- pub user_usec: Second,16+ pub user_usec: f64,17 18 /// Total amount of time spent executing in kernel mode19- pub system_usec: Second,19+ pub system_usec: f64,20 21 /// Maximum amount of memory used by the process, in bytes22 pub memory_usage_byte: i64,23 }24 25 #[allow(clippy::useless_conversion)]26-fn timeval_to_seconds(tv: libc::timeval) -> Second {26+fn timeval_to_seconds(tv: libc::timeval) -> f64 {27 const MICROSEC_PER_SEC: i64 = 1000 * 1000;28 (i64::from(tv.tv_sec) * MICROSEC_PER_SEC + i64::from(tv.tv_usec)) as f64 * 1e-629 }30 36 unmodified lines67 pub fn start() -> Self {68 Self {}69 }70 71- pub fn stop(&self, child: Child) -> Result<(ExitStatus, Second, Second, u64)> {71+ pub fn stop(&self, child: Child) -> Result<(ExitStatus, Second, Second, Byte)> {72 let (status, usage) = wait4(child)?;73 Ok((74 status,75- usage.user_usec,76- usage.system_usec,77- u64::try_from(usage.memory_usage_byte).unwrap_or(0),75+ Second::new(usage.user_usec),76+ Second::new(usage.system_usec),77+ Byte::new(u64::try_from(usage.memory_usage_byte).unwrap_or(0)),78 ))79 }80 }modified:src/timer/wall_clock_timer.rs+3 added-4 removed
1 use std::time::Instant;2 3-use crate::quantity::{nanosecond, second, Time};3+use crate::benchmark::quantity::Second;4 5 pub struct WallClockTimer {6 start: Instant,7 }6 unmodified lines14 }15 16 pub fn stop(&self) -> Time {17 let duration = self.start.elapsed();18-19- Time::new::<second>(duration.as_secs() as f64)20- + Time::new::<nanosecond>(duration.subsec_nanos() as f64)18+ // TODO19+ Second::new(duration.as_secs() as f64 + f64::from(duration.subsec_nanos()) * 1e-9)20 }21 }modified:src/options.rs+4 added-3 removed
5 unmodified lines6 7 use anyhow::{bail, ensure};8 use clap::ArgMatches;9 10+use crate::benchmark::quantity::Second;11 use crate::command::Commands;12 use crate::error::OptionsError;12-use crate::quantity::{second, Time, TimeUnit};13+use crate::util::units::Unit;14 15 use anyhow::Result;16 17 #[cfg(not(windows))]238 unmodified lines256 fn default() -> Options {257 Options {258 run_bounds: RunBounds::default(),259 warmup_count: 0,259- min_benchmarking_time: Time::new::<second>(3.0),260+ min_benchmarking_time: Second::new(3.0),261 command_failure_action: CmdFailureAction::RaiseError,262 reference_command: None,263 reference_name: None,264 reference_index: None,177 unmodified lines442 _ => None,443 };444 445 if let Some(time) = matches.get_one::<String>("min-benchmarking-time") {445- options.min_benchmarking_time = Time::new::<second>(446+ options.min_benchmarking_time = Second::new(447 time.parse::<f64>()448 .map_err(|e| OptionsError::FloatParsingError("min-benchmarking-time", e))?,449 );450 }127 unmodified linesmodified:Cargo.lock+10 added-2 removed
390 unmodified lines391 "rust_decimal",392 "serde",393 "serde_json",394 "shell-words",395+ "static_assertions",396+ "statistical",397 "tempfile",398 "thiserror",399 "uom",400 "windows-sys 0.61.2",418 unmodified lines819 source = "registry+https://github.com/rust-lang/crates.io-index"820 checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"821 822 [[package]]821-name = "strip-ansi-escapes"822-version = "0.2.1"823+name = "static_assertions"824+version = "1.1.0"825 source = "registry+https://github.com/rust-lang/crates.io-index"826+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"827+828+[[package]]829+name = "statistical"830+version = "1.0.0"831+source = "registry+https://github.com/rust-lang/crates.io-index"832 checksum = "2a8f8038e7e7969abb3f1b7c2a811225e9296da208539e0f79c5251d6cac0025"833 dependencies = [834 "vte",835 ]355 unmodified linesmodified:Cargo.toml+1 added-1 removed
26 unmodified lines27 rand = "0.10"28 shell-words = "1.1"29 thiserror = "2.0"30 anyhow = "1.0"31-uom = { version = "0.36.0", default-features = false, features = ["std", "si", "f64"] }31+static_assertions = "1.1.0"32 33 [target.'cfg(not(windows))'.dependencies]34 libc = "0.2"35 48 unmodified lines