Merge pull request #967 from sharkdp/codex/quantity-formatting
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Extract typed quantity formatting
authored by David Peter · committed by GitHub · parents 88a9150, 6f557e0 · Browse files · 6 files·+303 added−128 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+303 added−128 removed
- other:+303 added−128 removed
Provenance
- Commit
a6c3010- Tree
e9691d5- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
88a9150- Parent 2
6f557e0
6 files changed+303 added−128 removed
modified:src/benchmark/mod.rs+14 added-15 removed
15 unmodified lines16 use crate::output::console_writeln;17 use crate::output::progress_bar::get_progress_bar;18 use crate::output::warnings::{OutlierWarningOptions, Warnings};19 use crate::parameter::ParameterNameAndValue;20-use crate::quantity::{21- byte, const_time_from_seconds, format_duration, format_duration_unit, ratio, second, Time, Zero,22-};20+use crate::quantity::{byte, const_time_from_seconds, ratio, second, FormatQuantity, Time, Zero};21 use crate::util::exit_code::extract_exit_code;22 use benchmark_result::BenchmarkResult;23 use measurement::{Measurement, Measurements};24 266 unmodified lines291 for i in 0..count_remaining {292 run_preparation_command()?;293 294 let msg = {297- let mean = format_duration(298- measurements.time_wall_clock_mean().get::<second>(),299- self.options.time_unit,300- );295+ let t_wall_clock_mean = measurements.time_wall_clock_mean();296+ let time_unit = self297+ .options298+ .time_unit299+ .unwrap_or(t_wall_clock_mean.suitable_unit());300+ let mean = t_wall_clock_mean.format(time_unit);301 format!("Current estimate: {}", mean.to_string().green())302 };303 304 if let Some(bar) = progress_bar.as_ref() {34 unmodified lines339 let user_mean = measurements.time_user_mean();340 let system_mean = measurements.time_system_mean();341 342 // Formatting and console output343- let (mean_str, time_unit) =344- format_duration_unit(t_mean.get::<second>(), self.options.time_unit);345- let min_str = format_duration(t_min.get::<second>(), Some(time_unit));346- let max_str = format_duration(t_max.get::<second>(), Some(time_unit));343+ let time_unit = self.options.time_unit.unwrap_or(t_mean.suitable_unit());344+ let mean_str = t_mean.format(time_unit);345+ let min_str = t_min.format(time_unit);346+ let max_str = t_max.format(time_unit);347 let num_str = format!("{t_num} runs");348 349- let user_str = format_duration(user_mean.get::<second>(), Some(time_unit));350- let system_str = format_duration(system_mean.get::<second>(), Some(time_unit));349+ let user_str = user_mean.format(time_unit);350+ let system_str = system_mean.format(time_unit);351 352 if self.options.output_style != OutputStyleOption::Disabled {353 let mut stdout = io::stdout().lock();354 if measurements.len() == 1 {6 unmodified lines361 user_str.blue(),362 system_str.blue()363 )?;364 } else {365- let stddev_str =366- format_duration(t_stddev.unwrap().get::<second>(), Some(time_unit));365+ let stddev_str = t_stddev.unwrap().format(time_unit);366 367 console_writeln!(368 stdout,369 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",112 unmodified linesmodified:src/export/markup.rs+6 added-6 removed
1 use crate::benchmark::relative_speed::BenchmarkResultWithRelativeSpeed;2 use crate::benchmark::{benchmark_result::BenchmarkResult, relative_speed};3 use crate::options::SortOrder;4-use crate::quantity::{format_duration_value, TimeUnit};4+use crate::quantity::{second, FormatQuantity, IsUnit, Time, TimeUnit};5 6 use super::Exporter;7 use anyhow::Result;8 40 unmodified lines49 // prepare data row strings50 let cmd_str = measurement51 .command_with_unused_parameters52 .replace('|', "\\|");53- let mean_str = format_duration_value(measurement.mean, Some(unit)).0;53+ let mean_str = Time::new::<second>(measurement.mean).format_value(unit);54 let stddev_str = if let Some(stddev) = measurement.stddev {55- format!(" ± {}", format_duration_value(stddev, Some(unit)).0)55+ format!(" ± {}", Time::new::<second>(stddev).format_value(unit))56 } else {57 "".into()58 };59- let min_str = format_duration_value(measurement.min, Some(unit)).0;60- let max_str = format_duration_value(measurement.max, Some(unit)).0;59+ let min_str = Time::new::<second>(measurement.min).format_value(unit);60+ let max_str = Time::new::<second>(measurement.max).format_value(unit);61 let rel_str = format!("{:.2}", entry.relative_speed);62 let rel_stddev_str = if entry.is_reference {63 "".into()64 } else if let Some(stddev) = entry.relative_speed_stddev {35 unmodified lines100 101 fn determine_unit_from_results(results: &[BenchmarkResult]) -> TimeUnit {102 if let Some(first_result) = results.first() {103 // Use the first BenchmarkResult entry to determine the unit for all entries.104- format_duration_value(first_result.mean, None).1104+ Time::new::<second>(first_result.mean).suitable_unit()105 } else {106 // Default to `Second`.107 TimeUnit::Second108 }16 unmodified linesmodified:src/output/warnings.rs+4 added-4 removed
1 use std::fmt;2 3 use crate::benchmark::MIN_EXECUTION_TIME;4-use crate::quantity::{format_duration, second, Time};4+use crate::quantity::{FormatQuantity, Time, TimeUnit};5 6 pub struct OutlierWarningOptions {7 pub warmup_in_use: bool,8 pub prepare_in_use: bool,11 unmodified lines20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {21 match *self {22 Warnings::FastExecutionTime => write!(23 f,24- "Command took less than {:.0} ms to complete. Note that the results might be \24+ "Command took less than {} ms to complete. Note that the results might be \25 inaccurate because hyperfine can not calibrate the shell startup time much \26 more precise than this limit. You can try to use the `-N`/`--shell=none` \27 option to disable the shell completely.",28- MIN_EXECUTION_TIME.get::<second>() * 1e328+ 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,33 "The first benchmarking run for this command was significantly slower than the \34 rest ({time}). This could be caused by (filesystem) caches that were not filled until \35 after the first run. {hints}",36- time=format_duration(time_first_run.get::<second>(), None),36+ time=time_first_run.format_auto(),37 hints=match (options.warmup_in_use, options.prepare_in_use) {38 (true, true) => "You are already using both the '--warmup' option as well \39 as the '--prepare' option. Consider re-running the benchmark on a quiet system. \40 Maybe it was a random outlier. Alternatively, consider increasing the warmup \28 unmodified linesmodified:src/quantity/mod.rs+143 added-77 removed
1 use std::marker::PhantomData;2 3+use uom::si;4+5+pub use si::f64::{Information, Ratio, Time};6+pub use si::information::{byte, gibibyte, kibibyte, mebibyte, tebibyte};7+pub use si::ratio::ratio;8+pub use si::time::{hour, microsecond, millisecond, minute, nanosecond, second};9 pub use uom::num_traits::Zero;4-pub use uom::si::f64::{Information, Ratio, Time};5-pub use uom::si::information::byte;6-#[cfg(any(not(windows), test))]7-pub use uom::si::information::kibibyte;8-pub use uom::si::ratio::ratio;9-#[cfg(any(not(windows), test))]10-pub use uom::si::time::microsecond;11-pub use uom::si::time::{nanosecond, second};10 13-pub use units::TimeUnit;11+pub use units::{InformationUnit, IsUnit, TimeUnit};12 13 pub mod statistics;14 mod units;15 16+pub trait FormatQuantity {17+ type Unit;18+19+ fn suitable_unit(&self) -> Self::Unit;20+21+ fn format_with_precision(&self, unit: Self::Unit, precision: usize) -> String;22+ fn format(&self, unit: Self::Unit) -> String;23+ fn format_auto(&self) -> String;24+ fn format_value(&self, unit: Self::Unit) -> String;25+}26+27+impl FormatQuantity for Time {28+ type Unit = TimeUnit;29+30+ fn suitable_unit(&self) -> TimeUnit {31+ if *self < Time::new::<millisecond>(1.0) {32+ TimeUnit::MicroSecond33+ } else if *self < Time::new::<second>(1.0) {34+ TimeUnit::MilliSecond35+ } else {36+ TimeUnit::Second37+ }38+ }39+40+ /// Format the time duration in the given unit with the given precision.41+ fn format_with_precision(&self, u: TimeUnit, precision: usize) -> String {42+ u.format(*self, precision)43+ }44+45+ /// Format the time duration in the given unit.46+ fn format(&self, unit: TimeUnit) -> String {47+ let value = self.format_with_precision(unit, unit.preferred_precision());48+ format!("{} {}", value, unit.short_name())49+ }50+51+ /// Format the given time duration. The unit will be determined automatically.52+ fn format_auto(&self) -> String {53+ self.format(self.suitable_unit())54+ }55+56+ /// Like `format`, but without displaying the unit.57+ fn format_value(&self, unit: TimeUnit) -> String {58+ self.format_with_precision(unit, unit.preferred_precision())59+ }60+}61+62 pub const fn const_time_from_seconds(value: f64) -> Time {63 // Quantity::new in uom is not yet const: https://docs.rs/uom/0.36.0/uom/si/struct.Quantity.html64 Time {65 dimension: PhantomData,1 unmodified line67 value,68 }69 }70 27-/// Format the given duration as a string. The output-unit can be enforced by setting `unit` to28-/// `Some(target_unit)`. If `unit` is `None`, it will be determined automatically.29-pub fn format_duration(duration: f64, unit: Option<TimeUnit>) -> String {30- let (duration_fmt, _) = format_duration_unit(duration, unit);31- duration_fmt32-}71+impl FormatQuantity for Information {72+ type Unit = InformationUnit;73 34-/// Like `format_duration`, but returns the target unit as well.35-pub fn format_duration_unit(duration: f64, unit: Option<TimeUnit>) -> (String, TimeUnit) {36- let (out_str, out_unit) = format_duration_value(duration, unit);74+ fn suitable_unit(&self) -> InformationUnit {75+ if *self < Information::new::<kibibyte>(1.0) {76+ InformationUnit::Byte77+ } else if *self < Information::new::<mebibyte>(1.0) {78+ InformationUnit::KibiByte79+ } else if *self < Information::new::<gibibyte>(1.0) {80+ InformationUnit::MebiByte81+ } else {82+ InformationUnit::GibiByte83+ }84+ }85 86+ /// Format the information in the given unit with the given precision.87+ fn format_with_precision(&self, u: InformationUnit, precision: usize) -> String {38- (format!("{} {}", out_str, out_unit.short_name()), out_unit)39-}88+ u.format(*self, precision)89+ }90 41-/// Like `format_duration`, but returns the target unit as well.42-pub fn format_duration_value(duration: f64, unit: Option<TimeUnit>) -> (String, TimeUnit) {43- if (duration < 0.001 && unit.is_none()) || unit == Some(TimeUnit::MicroSecond) {44- (45- TimeUnit::MicroSecond.format(duration),46- TimeUnit::MicroSecond,47- )48- } else if (duration < 1.0 && unit.is_none()) || unit == Some(TimeUnit::MilliSecond) {49- (50- TimeUnit::MilliSecond.format(duration),51- TimeUnit::MilliSecond,52- )53- } else {54- let unit = unit.unwrap_or(TimeUnit::Second);55- (unit.format(duration), unit)91+ /// Format the information in the given unit.92+ fn format(&self, unit: InformationUnit) -> String {93+ let value = self.format_with_precision(unit, unit.preferred_precision());94+ format!("{} {}", value, unit.short_name())95 }57-}96 59-#[cfg(test)]60-use uom::si::time::millisecond;97+ /// Format the given information. The unit will be determined automatically.98+ fn format_auto(&self) -> String {99+ self.format(self.suitable_unit())100+ }101 102+ /// Like `format`, but without displaying the unit.103+ fn format_value(&self, unit: InformationUnit) -> String {104+ self.format_with_precision(unit, unit.preferred_precision())105+ }106+}107+108 #[test]109 fn test_time() {110 let time = Time::new::<millisecond>(123.4);111 assert_eq!(time.get::<millisecond>(), 123.4);19 unmodified lines131 assert_eq!(largest_exactly_representable.get::<pebibyte>(), 8.);132 }133 134 #[test]89-fn test_format_duration_unit_basic() {90- let (out_str, out_unit) = format_duration_unit(1.3, None);135+fn test_suiteable_unit_time() {136+ assert_eq!(Time::new::<second>(1.3).suitable_unit(), TimeUnit::Second);137+ assert_eq!(Time::new::<second>(1.0).suitable_unit(), TimeUnit::Second);138+ assert_eq!(139+ Time::new::<second>(0.999).suitable_unit(),140+ TimeUnit::MilliSecond141+ );142+ assert_eq!(143+ Time::new::<second>(0.0005).suitable_unit(),144+ TimeUnit::MicroSecond145+ );146+ assert_eq!(147+ Time::new::<second>(0.).suitable_unit(),148+ TimeUnit::MicroSecond149+ );150+ assert_eq!(151+ Time::new::<second>(1000.0).suitable_unit(),152+ TimeUnit::Second153+ );154+}155 92- assert_eq!("1.300 s", out_str);93- assert_eq!(TimeUnit::Second, out_unit);156+#[test]157+fn test_suitable_unit_information() {158+ assert_eq!(159+ Information::new::<byte>(512.0).suitable_unit(),160+ InformationUnit::Byte161+ );162+ assert_eq!(163+ Information::new::<byte>(2048.0).suitable_unit(),164+ InformationUnit::KibiByte165+ );166+ assert_eq!(167+ Information::new::<byte>(2_097_152.0).suitable_unit(),168+ InformationUnit::MebiByte169+ );170+ assert_eq!(171+ Information::new::<byte>(2_147_483_648.0).suitable_unit(),172+ InformationUnit::GibiByte173+ );174+}175 95- let (out_str, out_unit) = format_duration_unit(1.0, None);176+#[test]177+fn test_format() {178+ let time = Time::new::<millisecond>(123.4);179+ assert_eq!(time.format(TimeUnit::Second), "0.123 s");180+ assert_eq!(time.format(TimeUnit::MilliSecond), "123.4 ms");181+ assert_eq!(time.format_auto(), "123.4 ms");182+ assert_eq!(time.format(TimeUnit::MicroSecond), "123400.0 µs");183 97- assert_eq!("1.000 s", out_str);98- assert_eq!(TimeUnit::Second, out_unit);99-100- let (out_str, out_unit) = format_duration_unit(0.999, None);101-102- assert_eq!("999.0 ms", out_str);103- assert_eq!(TimeUnit::MilliSecond, out_unit);104-105- let (out_str, out_unit) = format_duration_unit(0.0005, None);106-107- assert_eq!("500.0 µs", out_str);108- assert_eq!(TimeUnit::MicroSecond, out_unit);109-110- let (out_str, out_unit) = format_duration_unit(0.0, None);111-112- assert_eq!("0.0 µs", out_str);113- assert_eq!(TimeUnit::MicroSecond, out_unit);114-115- let (out_str, out_unit) = format_duration_unit(1000.0, None);116-117- assert_eq!("1000.000 s", out_str);118- assert_eq!(TimeUnit::Second, out_unit);184+ let peak_memory_usage = Information::new::<kibibyte>(8.);185+ assert_eq!(peak_memory_usage.format_auto(), "8.0 KiB");186+ assert_eq!(peak_memory_usage.format(InformationUnit::Byte), "8192 B");187+ assert_eq!(188+ peak_memory_usage.format(InformationUnit::KibiByte),189+ "8.0 KiB"190+ );191 }192 193 #[test]194 fn test_format_duration_unit_with_unit() {123- let (out_str, out_unit) = format_duration_unit(1.3, Some(TimeUnit::Second));195+ let out = Time::new::<second>(1.3).format(TimeUnit::Second);196+ assert_eq!("1.300 s", out);197 125- assert_eq!("1.300 s", out_str);126- assert_eq!(TimeUnit::Second, out_unit);198+ let out = Time::new::<second>(1.3).format(TimeUnit::MilliSecond);199+ assert_eq!("1300.0 ms", out);200 128- let (out_str, out_unit) = format_duration_unit(1.3, Some(TimeUnit::MilliSecond));129-130- assert_eq!("1300.0 ms", out_str);131- assert_eq!(TimeUnit::MilliSecond, out_unit);132-133- let (out_str, out_unit) = format_duration_unit(1.3, Some(TimeUnit::MicroSecond));134-135- assert_eq!("1300000.0 µs", out_str);136- assert_eq!(TimeUnit::MicroSecond, out_unit);201+ let out = Time::new::<second>(1.3).format(TimeUnit::MicroSecond);202+ assert_eq!("1300000.0 µs", out);203 }modified:src/quantity/units.rs+135 added-25 removed
1-//! This module contains common units.1+//! This module contains common units for time and information quantities.2 3+use std::marker::PhantomData;4+5+use crate::quantity::{6+ byte, gibibyte, hour, kibibyte, mebibyte, microsecond, millisecond, minute, second, tebibyte,7+ Information, Time,8+};9+10+pub trait IsUnit {11+ type Quantity;12+13+ fn dispatch(&self) -> Box<dyn UnitImpl<Quantity = Self::Quantity>>;14+15+ fn preferred_precision(&self) -> usize;16+17+ fn short_name(&self) -> &'static str {18+ self.dispatch().short_name()19+ }20+21+ fn format(&self, value: Self::Quantity, precision: usize) -> String {22+ self.dispatch().format_value(value, precision)23+ }24+}25+26 /// Supported time units27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]28 pub enum TimeUnit {6- Second,7- MilliSecond,29 MicroSecond,30+ MilliSecond,31+ Second,32 Minute,33 Hour,34 }35 13-impl TimeUnit {14- /// The abbreviation of the TimeUnit.15- pub fn short_name(self) -> String {36+impl IsUnit for TimeUnit {37+ type Quantity = Time;38+39+ fn dispatch(&self) -> Box<dyn UnitImpl<Quantity = Time>> {40 match self {17- TimeUnit::Second => String::from("s"),18- TimeUnit::MilliSecond => String::from("ms"),19- TimeUnit::MicroSecond => String::from("µs"),20- TimeUnit::Minute => String::from("min"),21- TimeUnit::Hour => String::from("h"),41+ TimeUnit::MicroSecond => Box::new(TimeUnitDispatcher::<microsecond>::new()),42+ TimeUnit::MilliSecond => Box::new(TimeUnitDispatcher::<millisecond>::new()),43+ TimeUnit::Second => Box::new(TimeUnitDispatcher::<second>::new()),44+ TimeUnit::Minute => Box::new(TimeUnitDispatcher::<minute>::new()),45+ TimeUnit::Hour => Box::new(TimeUnitDispatcher::<hour>::new()),46 }47 }48 25- /// Returns the value in seconds formatted for the TimeUnit.26- pub fn format(self, value: f64) -> String {49+ fn preferred_precision(&self) -> usize {50 match self {28- TimeUnit::Second => format!("{value:.3}"),29- TimeUnit::MilliSecond => format!("{:.1}", value * 1e3),30- TimeUnit::MicroSecond => format!("{:.1}", value * 1e6),31- TimeUnit::Minute => format!("{:.1}", value / 60.0),32- TimeUnit::Hour => format!("{:.1}", value / 3600.0),51+ TimeUnit::Second => 3,52+ _ => 1,53 }54 }55 }56 57+/// Supported information units58+#[derive(Debug, Clone, Copy, PartialEq, Eq)]59+60+pub enum InformationUnit {61+ Byte,62+ KibiByte,63+ MebiByte,64+ GibiByte,65+ TebiByte,66+}67+68+impl IsUnit for InformationUnit {69+ type Quantity = Information;70+71+ fn dispatch(&self) -> Box<dyn UnitImpl<Quantity = Information>> {72+ match self {73+ InformationUnit::Byte => Box::new(InformationUnitDispatcher::<byte>::new()),74+ InformationUnit::KibiByte => Box::new(InformationUnitDispatcher::<kibibyte>::new()),75+ InformationUnit::MebiByte => Box::new(InformationUnitDispatcher::<mebibyte>::new()),76+ InformationUnit::GibiByte => Box::new(InformationUnitDispatcher::<gibibyte>::new()),77+ InformationUnit::TebiByte => Box::new(InformationUnitDispatcher::<tebibyte>::new()),78+ }79+ }80+81+ fn preferred_precision(&self) -> usize {82+ match self {83+ InformationUnit::Byte => 0,84+ _ => 1,85+ }86+ }87+}88+89+pub trait UnitImpl {90+ type Quantity;91+92+ fn short_name(&self) -> &'static str;93+ fn format_value(&self, value: Self::Quantity, precision: usize) -> String;94+}95+96+struct TimeUnitDispatcher<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> {97+ u: PhantomData<U>,98+}99+100+impl<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> TimeUnitDispatcher<U> {101+ fn new() -> Self {102+ TimeUnitDispatcher { u: PhantomData }103+ }104+}105+106+impl<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> UnitImpl for TimeUnitDispatcher<U> {107+ type Quantity = Time;108+109+ fn short_name(&self) -> &'static str {110+ U::abbreviation()111+ }112+113+ fn format_value(&self, value: Time, precision: usize) -> String {114+ format!("{value:.precision$}", value = value.get::<U>())115+ }116+}117+118+struct InformationUnitDispatcher<U: uom::si::information::Unit + uom::Conversion<f64, T = f64>> {119+ u: PhantomData<U>,120+}121+122+impl<U: uom::si::information::Unit + uom::Conversion<f64, T = f64>> InformationUnitDispatcher<U> {123+ fn new() -> Self {124+ InformationUnitDispatcher { u: PhantomData }125+ }126+}127+128+impl<U: uom::si::information::Unit + uom::Conversion<f64, T = f64>> UnitImpl129+ for InformationUnitDispatcher<U>130+{131+ type Quantity = Information;132+133+ fn short_name(&self) -> &'static str {134+ U::abbreviation()135+ }136+137+ fn format_value(&self, value: Information, precision: usize) -> String {138+ format!("{value:.precision$}", value = value.get::<U>())139+ }140+}141+142 #[test]38-fn test_unit_short_name() {143+fn test_time_unit_short_name() {144 assert_eq!("s", TimeUnit::Second.short_name());145 assert_eq!("ms", TimeUnit::MilliSecond.short_name());146 assert_eq!("µs", TimeUnit::MicroSecond.short_name());147 assert_eq!("min", TimeUnit::Minute.short_name());2 unmodified lines150 151 // Note - the values are rounded when formatted.152 #[test]153 fn test_unit_format() {49- let value: f64 = 123.456789;50- assert_eq!("123.457", TimeUnit::Second.format(value));51- assert_eq!("123456.8", TimeUnit::MilliSecond.format(value));154+ use crate::quantity::FormatQuantity;155 53- assert_eq!("1234.6", TimeUnit::MicroSecond.format(0.00123456));54- assert_eq!("2.1", TimeUnit::Minute.format(value));55- assert_eq!("0.0", TimeUnit::Hour.format(value));156+ let value = Time::new::<second>(123.456789);157+ assert_eq!("123.457", value.format_value(TimeUnit::Second));158+ assert_eq!("123456.8", value.format_value(TimeUnit::MilliSecond));159+160+ assert_eq!(161+ "1234.6",162+ Time::new::<second>(0.00123456).format_value(TimeUnit::MicroSecond)163+ );164+ assert_eq!("2.1", value.format_value(TimeUnit::Minute));165+ assert_eq!("0.0", value.format_value(TimeUnit::Hour));166 }modified:src/main.rs+1 added-1 removed
23 unmodified lines24 pub mod options;25 pub mod outlier_detection;26 pub mod output;27 pub mod parameter;28-mod quantity;28+pub mod quantity;29 pub mod timer;30 pub mod util;31 32 fn run() -> Result<()> {44 unmodified lines