Skip to content
Myr

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

6 files+303 added−128 removed

modified:src/benchmark/mod.rs+14 added-15 removed
15 unmodified lines
16use crate::output::console_writeln;17use crate::output::progress_bar::get_progress_bar;18use crate::output::warnings::{OutlierWarningOptions, Warnings};19use crate::parameter::ParameterNameAndValue;20use crate::quantity::{21 byte, const_time_from_seconds, format_duration, format_duration_unit, ratio, second, Time, Zero,22};20use crate::quantity::{byte, const_time_from_seconds, ratio, second, FormatQuantity, Time, Zero};21use crate::util::exit_code::extract_exit_code;22use benchmark_result::BenchmarkResult;23use measurement::{Measurement, Measurements};24
266 unmodified lines
291 for i in 0..count_remaining {292 run_preparation_command()?;293294 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 };303304 if let Some(bar) = progress_bar.as_ref() {
34 unmodified lines
339 let user_mean = measurements.time_user_mean();340 let system_mean = measurements.time_system_mean();341342 // 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");348349 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);351352 if self.options.output_style != OutputStyleOption::Disabled {353 let mut stdout = io::stdout().lock();354 if measurements.len() == 1 {
6 unmodified lines
361 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);366367 console_writeln!(368 stdout,369 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",
112 unmodified lines
modified:src/export/markup.rs+6 added-6 removed
1use crate::benchmark::relative_speed::BenchmarkResultWithRelativeSpeed;2use crate::benchmark::{benchmark_result::BenchmarkResult, relative_speed};3use crate::options::SortOrder;4use crate::quantity::{format_duration_value, TimeUnit};4use crate::quantity::{second, FormatQuantity, IsUnit, Time, TimeUnit};56use super::Exporter;7use anyhow::Result;8
40 unmodified lines
49 // 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 lines
100101fn 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 lines
modified:src/output/warnings.rs+4 added-4 removed
1use std::fmt;23use crate::benchmark::MIN_EXECUTION_TIME;4use crate::quantity::{format_duration, second, Time};4use crate::quantity::{FormatQuantity, Time, TimeUnit};56pub struct OutlierWarningOptions {7 pub warmup_in_use: bool,8 pub prepare_in_use: bool,
11 unmodified lines
20 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 lines
modified:src/quantity/mod.rs+143 added-77 removed
1use std::marker::PhantomData;23use uom::si;45pub use si::f64::{Information, Ratio, Time};6pub use si::information::{byte, gibibyte, kibibyte, mebibyte, tebibyte};7pub use si::ratio::ratio;8pub use si::time::{hour, microsecond, millisecond, minute, nanosecond, second};9pub use uom::num_traits::Zero;4pub use uom::si::f64::{Information, Ratio, Time};5pub use uom::si::information::byte;6#[cfg(any(not(windows), test))]7pub use uom::si::information::kibibyte;8pub use uom::si::ratio::ratio;9#[cfg(any(not(windows), test))]10pub use uom::si::time::microsecond;11pub use uom::si::time::{nanosecond, second};1013pub use units::TimeUnit;11pub use units::{InformationUnit, IsUnit, TimeUnit};1213pub mod statistics;14mod units;1516pub trait FormatQuantity {17 type Unit;1819 fn suitable_unit(&self) -> Self::Unit;2021 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}2627impl FormatQuantity for Time {28 type Unit = TimeUnit;2930 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 }3940 /// 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 }4445 /// 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 }5051 /// Format the given time duration. The unit will be determined automatically.52 fn format_auto(&self) -> String {53 self.format(self.suitable_unit())54 }5556 /// 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}6162pub 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 line
67 value,68 }69}7027/// 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.29pub fn format_duration(duration: f64, unit: Option<TimeUnit>) -> String {30 let (duration_fmt, _) = format_duration_unit(duration, unit);31 duration_fmt32}71impl FormatQuantity for Information {72 type Unit = InformationUnit;7334/// Like `format_duration`, but returns the target unit as well.35pub 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 }8586 /// 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 }9041/// Like `format_duration`, but returns the target unit as well.42pub 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}9659#[cfg(test)]60use 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 }101102 /// 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}107108#[test]109fn test_time() {110 let time = Time::new::<millisecond>(123.4);111 assert_eq!(time.get::<millisecond>(), 123.4);
19 unmodified lines
131 assert_eq!(largest_exactly_representable.get::<pebibyte>(), 8.);132}133134#[test]89fn test_format_duration_unit_basic() {90 let (out_str, out_unit) = format_duration_unit(1.3, None);135fn 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}15592 assert_eq!("1.300 s", out_str);93 assert_eq!(TimeUnit::Second, out_unit);156#[test]157fn 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}17595 let (out_str, out_unit) = format_duration_unit(1.0, None);176#[test]177fn 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");18397 assert_eq!("1.000 s", out_str);98 assert_eq!(TimeUnit::Second, out_unit);99100 let (out_str, out_unit) = format_duration_unit(0.999, None);101102 assert_eq!("999.0 ms", out_str);103 assert_eq!(TimeUnit::MilliSecond, out_unit);104105 let (out_str, out_unit) = format_duration_unit(0.0005, None);106107 assert_eq!("500.0 µs", out_str);108 assert_eq!(TimeUnit::MicroSecond, out_unit);109110 let (out_str, out_unit) = format_duration_unit(0.0, None);111112 assert_eq!("0.0 µs", out_str);113 assert_eq!(TimeUnit::MicroSecond, out_unit);114115 let (out_str, out_unit) = format_duration_unit(1000.0, None);116117 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}192193#[test]194fn 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);197125 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);200128 let (out_str, out_unit) = format_duration_unit(1.3, Some(TimeUnit::MilliSecond));129130 assert_eq!("1300.0 ms", out_str);131 assert_eq!(TimeUnit::MilliSecond, out_unit);132133 let (out_str, out_unit) = format_duration_unit(1.3, Some(TimeUnit::MicroSecond));134135 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.23use std::marker::PhantomData;45use crate::quantity::{6 byte, gibibyte, hour, kibibyte, mebibyte, microsecond, millisecond, minute, second, tebibyte,7 Information, Time,8};910pub trait IsUnit {11 type Quantity;1213 fn dispatch(&self) -> Box<dyn UnitImpl<Quantity = Self::Quantity>>;1415 fn preferred_precision(&self) -> usize;1617 fn short_name(&self) -> &'static str {18 self.dispatch().short_name()19 }2021 fn format(&self, value: Self::Quantity, precision: usize) -> String {22 self.dispatch().format_value(value, precision)23 }24}2526/// Supported time units27#[derive(Debug, Clone, Copy, PartialEq, Eq)]28pub enum TimeUnit {6 Second,7 MilliSecond,29 MicroSecond,30 MilliSecond,31 Second,32 Minute,33 Hour,34}3513impl TimeUnit {14 /// The abbreviation of the TimeUnit.15 pub fn short_name(self) -> String {36impl IsUnit for TimeUnit {37 type Quantity = Time;3839 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 }4825 /// 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}5657/// Supported information units58#[derive(Debug, Clone, Copy, PartialEq, Eq)]5960pub enum InformationUnit {61 Byte,62 KibiByte,63 MebiByte,64 GibiByte,65 TebiByte,66}6768impl IsUnit for InformationUnit {69 type Quantity = Information;7071 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 }8081 fn preferred_precision(&self) -> usize {82 match self {83 InformationUnit::Byte => 0,84 _ => 1,85 }86 }87}8889pub trait UnitImpl {90 type Quantity;9192 fn short_name(&self) -> &'static str;93 fn format_value(&self, value: Self::Quantity, precision: usize) -> String;94}9596struct TimeUnitDispatcher<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> {97 u: PhantomData<U>,98}99100impl<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> TimeUnitDispatcher<U> {101 fn new() -> Self {102 TimeUnitDispatcher { u: PhantomData }103 }104}105106impl<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> UnitImpl for TimeUnitDispatcher<U> {107 type Quantity = Time;108109 fn short_name(&self) -> &'static str {110 U::abbreviation()111 }112113 fn format_value(&self, value: Time, precision: usize) -> String {114 format!("{value:.precision$}", value = value.get::<U>())115 }116}117118struct InformationUnitDispatcher<U: uom::si::information::Unit + uom::Conversion<f64, T = f64>> {119 u: PhantomData<U>,120}121122impl<U: uom::si::information::Unit + uom::Conversion<f64, T = f64>> InformationUnitDispatcher<U> {123 fn new() -> Self {124 InformationUnitDispatcher { u: PhantomData }125 }126}127128impl<U: uom::si::information::Unit + uom::Conversion<f64, T = f64>> UnitImpl129 for InformationUnitDispatcher<U>130{131 type Quantity = Information;132133 fn short_name(&self) -> &'static str {134 U::abbreviation()135 }136137 fn format_value(&self, value: Information, precision: usize) -> String {138 format!("{value:.precision$}", value = value.get::<U>())139 }140}141142#[test]38fn test_unit_short_name() {143fn 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 lines
150151// Note - the values are rounded when formatted.152#[test]153fn 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;15553 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));159160 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 lines
24pub mod options;25pub mod outlier_detection;26pub mod output;27pub mod parameter;28mod quantity;28pub mod quantity;29pub mod timer;30pub mod util;3132fn run() -> Result<()> {
44 unmodified lines