Skip to content
Myr

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

15 files+384 added−272 removed

modified:src/benchmark/benchmark_result.rs+1 added-1 removed
1use std::collections::BTreeMap;23use serde::Serialize;45use crate::{benchmark::measurement::Measurements, util::units::Second};5use crate::benchmark::{measurement::Measurements, quantity::Second};67/// Parameter value and whether it was used in the command line template8#[derive(Debug, Default, Clone, Serialize, PartialEq)]9pub struct Parameter {
54 unmodified lines
modified:src/benchmark/executor.rs+25 added-16 removed
1#[cfg(windows)]2use std::os::windows::process::CommandExt;3use std::process::ExitStatus;45use crate::benchmark::quantity::mean;6use crate::benchmark::quantity::Byte;7use crate::benchmark::quantity::Second;8use crate::command::Command;9use crate::options::{10 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,11};
151 unmodified lines
163 fn calibrate(&mut self) -> Result<()> {164 Ok(())165 }166164 fn time_overhead(&self) -> Time {165 Time::zero()167 fn time_overhead(&self) -> Second {168 Second::zero()169 }170}171172pub struct ShellExecutor<'a> {
41 unmodified lines
214 &command.get_command_line(),215 )?;216217 // Subtract shell spawning time218 fn ensure_non_negative(time: Second) -> Second {219 if time < Second::zero() {220 Second::zero()221 } else {222 time223 }224 }225226 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 }233234 Ok((235 TimingResult {
18 unmodified lines
254 } else {255 None256 };257246 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![];261262 for _ in 0..COUNT {
37 unmodified lines
300 self.shell_spawning_time = Some(TimingResult {301 time_wall_clock: mean(&times_wall_clock),302 time_user: mean(&times_user),303 time_system: mean(&times_system),292 memory_usage_byte: 0,304 memory_usage_byte: Byte::new(0),305 });306307 Ok(())308 }
14 unmodified lines
323 }324325 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 lines
356357 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 lines
370 }371372 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}379380#[test]381fn 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
1use serde::Serialize;23use statistical::{mean, median, standard_deviation};3use crate::benchmark::quantity::{max, mean, median, min, standard_deviation, Byte, Second};4use crate::outlier_detection::modified_zscores;55use crate::util::units::Second;6use crate::{7 outlier_detection::modified_zscores,8 util::min_max::{max, min},9};106/// Performance metric measurements and exit code for a single run7#[derive(Debug, Clone, Serialize, PartialEq)]8pub struct Measurement {9 /// Elapsed wall clock time (real time)
4 unmodified lines
1415 /// Time spent in kernel mode16 pub system_time: Second,1723 /// 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,2021 /// Exit codes of the process22 pub exit_code: Option<i32>,23}
35 unmodified lines
59 /// 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();6268 let t_mean = mean(&times);69 if times.len() > 1 {63 if times.len() < 2 {70 Some(standard_deviation(&times, Some(t_mean)))71 } else {64 None65 } else {66 Some(standard_deviation(&times))67 }68 }6970 /// The median wall clock time
33 unmodified lines
104 )105 }106107 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 }116117 pub fn peak_memory_usage_mean(&self) -> Information {118 mean(self.measurements.iter().map(|m| m.peak_memory_usage))
2 unmodified lines
modified:src/benchmark/mod.rs+5 added-5 removed
10 unmodified lines
1112use crate::benchmark::benchmark_result::Parameter;13use crate::benchmark::executor::BenchmarkIteration;14use crate::benchmark::measurement::{Measurement, Measurements};15use crate::benchmark::quantity::{MilliSecond, Second};16use crate::command::Command;17use crate::options::{18 CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,19};
6 unmodified lines
26use crate::output::warnings::{OutlierWarningOptions, Warnings};27use crate::parameter::ParameterNameAndValue;28use crate::quantity::{byte, const_time_from_seconds, ratio, second, FormatQuantity, Time, Zero};29use crate::util::exit_code::extract_exit_code;29use crate::util::units::Second;30use benchmark_result::BenchmarkResult;31use measurement::{Measurement, Measurements};3233use anyhow::{anyhow, Result};
1 unmodified line
3536use self::executor::Executor;3738/// Threshold for warning about fast execution time39pub const MIN_EXECUTION_TIME: Time = const_time_from_seconds(5e-3);39pub const MIN_EXECUTION_TIME: MilliSecond = MilliSecond::new(5.);4041pub struct Benchmark<'a> {42 number: usize,43 command: &'a Command<'a>,
220 unmodified lines
264 None265 };266267 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 });271272 // Initial timing run
20 unmodified lines
293 );294 }295296 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 });300301 // Determine number of benchmark runs
131 unmodified lines
433 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 lines
modified:src/benchmark/quantity.rs+169 added-67 removed
1use std::fmt::{self, Display, Formatter};1use std::{2 fmt::{self, Display, Formatter},3 ops::{Add, Div, Sub},4};56use serde::Serialize;75#[derive(Debug, Clone, Serialize, PartialEq)]6enum MetricPrefix {7 Nano,8 Micro,9 Milli,10 None,8pub trait IsQuantity {9 type Value;1011 const IS_TIME: bool;12 const METRIC_PREFIX_TIME: i32;13 const IS_INFORMATION: bool;14 const BINARY_PREFIX_INFORMATION: i32;1516 fn unsafe_from(value: Self::Value) -> Self;17}1813impl 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 partialord20pub 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);2728impl<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;4243 fn unsafe_from(value: Self::Value) -> Self {44 Self(value)45 }46}4724#[derive(Debug, Clone, Serialize, PartialEq)]25enum BinaryPrefix {26 None,27 Kibi,28 Mebi,29 Gibi,30 Tebi,31}48type Time<const PREFIX: i32> = Quantity<f64, true, PREFIX, false, 0>;49type Information<const PREFIX: i32> = Quantity<u64, false, 0, true, PREFIX>;5033impl 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"),51pub type Second = Time<0>;52pub type MilliSecond = Time<-3>;53pub type MicroSecond = Time<-6>;5455pub type Byte = Information<0>;56pub type KibiByte = Information<10>;57pub type MebiByte = Information<20>;58pub type GibiByte = Information<30>;59pub type TebiByte = Information<40>;6061impl<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 }7273 pub fn zero() -> Self {74 Self::new(Value::default())75 }7677 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 }8485 self.086 }87}8845#[derive(Debug, Clone, Serialize, PartialEq)]46pub enum Unit {47 Second(MetricPrefix),48 Byte(BinaryPrefix),89impl<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);9293 TargetUnit::unsafe_from(self.0 * factor)94 }95}9651pub const SECOND: Unit = Unit::Second(MetricPrefix::None);52pub const MILLISECOND: Unit = Unit::Second(MetricPrefix::Milli);53pub const MICROSECOND: Unit = Unit::Second(MetricPrefix::Micro);54pub const BYTE: Unit = Unit::Byte(BinaryPrefix::None);97impl<const METRIC_PREFIX_TIME: i32> Add<Time<METRIC_PREFIX_TIME>> for Time<METRIC_PREFIX_TIME> {98 type Output = Time<METRIC_PREFIX_TIME>;9956impl 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}10465#[derive(Debug, Clone, Serialize, PartialEq)]66pub struct Quantity<Value> {67 value: Value,68 unit: Unit,105impl<const METRIC_PREFIX_TIME: i32> Sub<Time<METRIC_PREFIX_TIME>> for Time<METRIC_PREFIX_TIME> {106 type Output = Time<METRIC_PREFIX_TIME>;107108 fn sub(self, rhs: Time<METRIC_PREFIX_TIME>) -> Self::Output {109 Time::new(self.0 - rhs.0)110 }111}11271impl<Value> Quantity<Value> {72 pub fn new(value: Value, unit: Unit) -> Self {73 Self { value, unit }113impl<const METRIC_PREFIX_TIME: i32> Div<Time<METRIC_PREFIX_TIME>> for Time<METRIC_PREFIX_TIME> {114 type Output = f64;115116 fn div(self, rhs: Time<METRIC_PREFIX_TIME>) -> Self::Output {117 self.0 / rhs.0118 }119}12077impl<Value: Display> Display for Quantity<Value> {121impl<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}13283pub fn mean(values: &[Quantity<f64>]) -> Quantity<f64> {84 statistical::mean(values).unwrap()133impl<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}14687pub type Time = Quantity<f64>;88pub type Memory = Quantity<u64>;147macro_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}169170quantity_fn!(mean, values, statistical::mean(&values));171quantity_fn!(median, values, statistical::median(&values));172quantity_fn!(min, values, crate::util::min_max::min(&values));173quantity_fn!(max, values, crate::util::min_max::max(&values));174quantity_fn!(standard_deviation, values, {175 let mean_value = statistical::mean(&values);176 statistical::standard_deviation(&values, Some(mean_value))177});178179#[test]91fn basic() {92 let time = Time {93 value: 123.4,94 unit: Unit::Second(MetricPrefix::Milli),95 };180fn test_quantity() {181 let time = MilliSecond::new(123.4);182 assert_eq!(time.value_in::<MilliSecond>(), 123.4);183184 let time_s = time.convert_to::<Second>();185 approx::assert_relative_eq!(time_s.value_in::<Second>(), 0.1234);186187 let time_us = time.convert_to::<MicroSecond>();188 approx::assert_relative_eq!(time_us.value_in::<MicroSecond>(), 123400.0);189}190191#[test]192fn test_format() {193 let time = MilliSecond::new(123.4);194 assert_eq!(time.to_string(), "123.4 ms");19598 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}199200#[test]201fn 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
1use std::cmp::Ordering;23use super::benchmark_result::BenchmarkResult;4use crate::{5 options::SortOrder,6 quantity::{self, Ratio, Time, Zero},7};4use crate::{benchmark::quantity::Second, options::SortOrder};56#[derive(Debug)]7pub struct BenchmarkResultWithRelativeSpeed<'a> {8 pub result: &'a BenchmarkResult,
42 unmodified lines
51 // 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);5458 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 lines
113 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 lines
128 sort_order: SortOrder,129) -> Option<Vec<BenchmarkResultWithRelativeSpeed<'_>>> {130 let fastest = fastest_of(results);131134 if fastest.mean_wall_clock_time() == 0.0 {132 if fastest.mean_wall_clock_time() == Second::zero() {133 return None;134 }135136 Some(compute_relative_speeds(results, fastest, sort_order))
12 unmodified lines
149#[cfg(test)]150fn create_result(name: &str, mean: f64) -> BenchmarkResult {151 use std::collections::BTreeMap;152155 use crate::benchmark::measurement::{Measurement, Measurements};153 use crate::benchmark::{154 measurement::{Measurement, Measurements},155 quantity::Byte,156 };157158 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 lines
modified:src/export/csv.rs+28 added-37 removed
2 unmodified lines
3use csv::WriterBuilder;45use super::Exporter;6use crate::benchmark::benchmark_result::BenchmarkResult;7use crate::benchmark::quantity::Second;8use crate::options::SortOrder;9use crate::quantity::{FormatQuantity, TimeUnit};1011use anyhow::Result;
33 unmodified lines
45 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 lines
64 Ok(writer.into_inner()?)65 }66}6770#[cfg(test)]71use crate::benchmark::benchmark_result::Parameter;7273#[cfg(test)]74use crate::benchmark::measurement::{Measurement, Measurements};7568#[test]69fn 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};7374 use std::collections::BTreeMap;83 use std::process::ExitStatus;7576 let exporter = CsvExporter::default();7778 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 lines
123 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 lines
modified:src/export/tests.rs+97 added-96 removed
1use super::Exporter;2use crate::benchmark::benchmark_result::BenchmarkResult;3use crate::benchmark::measurement::{Measurement, Measurements};4use crate::benchmark::quantity::{Byte, Second};5use crate::export::asciidoc::AsciidocExporter;6use crate::export::orgmode::OrgmodeExporter;7use crate::quantity::{byte, second, Information, Time, TimeUnit, Zero};8use crate::{export::markdown::MarkdownExporter, options::SortOrder};
21 unmodified lines
30 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 line
57 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 lines
129 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 line
156 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 lines
228 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 line
255 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 lines
326 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 line
353 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 lines
modified:src/output/warnings.rs+3 added-3 removed
1use std::fmt;23use crate::benchmark::quantity::Second;4use crate::benchmark::MIN_EXECUTION_TIME;4use crate::quantity::{FormatQuantity, Time, TimeUnit};5use crate::output::format::format_duration;67pub struct OutlierWarningOptions {8 pub warmup_in_use: bool,9 pub prepare_in_use: bool,
11 unmodified lines
21 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 lines
modified:src/timer/mod.rs+2 added-2 removed
14 unmodified lines
1516#[cfg(target_os = "windows")]17use windows_sys::Win32::System::Threading::CREATE_SUSPENDED;1819use crate::benchmark::measurement::Measurement;19use crate::benchmark::quantity::{Byte, Second};20use wall_clock_timer::WallClockTimer;2122use std::io::Read;23use std::process::{ChildStdout, Command};
5 unmodified lines
29pub 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 lines
modified:src/timer/unix_timer.rs+8 added-8 removed
6 unmodified lines
7use std::process::{Child, ExitStatus};89use anyhow::Result;1011use crate::util::units::Second;11use crate::benchmark::quantity::{Byte, Second};1213#[derive(Debug, Copy, Clone)]14struct ResourceUsage {15 /// Total amount of time spent executing in user mode16 pub user_usec: Second,16 pub user_usec: f64,1718 /// Total amount of time spent executing in kernel mode19 pub system_usec: Second,19 pub system_usec: f64,2021 /// Maximum amount of memory used by the process, in bytes22 pub memory_usage_byte: i64,23}2425#[allow(clippy::useless_conversion)]26fn timeval_to_seconds(tv: libc::timeval) -> Second {26fn 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 lines
67 pub fn start() -> Self {68 Self {}69 }7071 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
1use std::time::Instant;23use crate::quantity::{nanosecond, second, Time};3use crate::benchmark::quantity::Second;45pub struct WallClockTimer {6 start: Instant,7}
6 unmodified lines
14 }1516 pub fn stop(&self) -> Time {17 let duration = self.start.elapsed();1819 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 lines
67use anyhow::{bail, ensure};8use clap::ArgMatches;910use crate::benchmark::quantity::Second;11use crate::command::Commands;12use crate::error::OptionsError;12use crate::quantity::{second, Time, TimeUnit};13use crate::util::units::Unit;1415use anyhow::Result;1617#[cfg(not(windows))]
238 unmodified lines
256 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 lines
442 _ => None,443 };444445 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 lines
modified:Cargo.lock+10 added-2 removed
390 unmodified lines
391 "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 lines
819source = "registry+https://github.com/rust-lang/crates.io-index"820checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"821822[[package]]821name = "strip-ansi-escapes"822version = "0.2.1"823name = "static_assertions"824version = "1.1.0"825source = "registry+https://github.com/rust-lang/crates.io-index"826checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"827828[[package]]829name = "statistical"830version = "1.0.0"831source = "registry+https://github.com/rust-lang/crates.io-index"832checksum = "2a8f8038e7e7969abb3f1b7c2a811225e9296da208539e0f79c5251d6cac0025"833dependencies = [834 "vte",835]
355 unmodified lines
modified:Cargo.toml+1 added-1 removed
26 unmodified lines
27rand = "0.10"28shell-words = "1.1"29thiserror = "2.0"30anyhow = "1.0"31uom = { version = "0.36.0", default-features = false, features = ["std", "si", "f64"] }31static_assertions = "1.1.0"3233[target.'cfg(not(windows))'.dependencies]34libc = "0.2"35
48 unmodified lines