Quantity API cleanup
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 0257df9 · Browse files · 10 files·+257 added−162 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+257 added−162 removed
- other:+257 added−162 removed
Provenance
- Commit
4badeb6- Tree
3db4cc5- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
David Peter <mail@david-peter.de>- Parent
0257df9
10 files changed+257 added−162 removed
modified:src/benchmark/mod.rs+11 added-10 removed
14 unmodified lines15 use crate::options::{16 CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,17 };18 use crate::outlier_detection::OUTLIER_THRESHOLD;19-use crate::output::format::{format_duration, format_duration_unit};19 use crate::output::console_writeln;20 use crate::output::progress_bar::{21 finish_initial_measurement, get_progress_bar, start_initial_measurement,22 };306 unmodified lines329 for i in 0..count_remaining {330 let benchmark_iteration = BenchmarkIteration::Benchmark(i + 1);331 332 let msg = {334- let mean =335- format_duration(measurements.time_wall_clock_mean(), self.options.time_unit);333+ let mean = measurements334+ .time_wall_clock_mean()335+ .format_auto(self.options.time_unit);336 format!("Current estimate: {}", mean.to_string().green())337 };338 339 if let Some(bar) = progress_bar.as_ref() {24 unmodified lines364 bar.finish_and_clear()365 }366 367 // Formatting and console output368- let (mean_str, time_unit) =369- format_duration_unit(measurements.time_wall_clock_mean(), self.options.time_unit);370- let min_str = format_duration(measurements.min(), Some(time_unit));371- let max_str = format_duration(measurements.max(), Some(time_unit));368+ let (mean_str, time_unit) = measurements369+ .time_wall_clock_mean()370+ .format_auto_with_unit(self.options.time_unit);371+ let min_str = measurements.min().format_auto(Some(time_unit));372+ let max_str = measurements.max().format_auto(Some(time_unit));373 let num_str = format!("{num_runs} runs", num_runs = measurements.len());374 374- let user_str = format_duration(measurements.time_user_mean(), Some(time_unit));375- let system_str = format_duration(measurements.time_system_mean(), Some(time_unit));375+ let user_str = measurements.time_user_mean().format_auto(Some(time_unit));376+ let system_str = measurements.time_system_mean().format_auto(Some(time_unit));377 378 if self.options.output_style != OutputStyleOption::Disabled {379 if measurements.len() == 1 {380 println!(4 unmodified lines385 user_str.blue(),386 system_str.blue()387 )?;388 } else {388- let stddev_str = format_duration(measurements.stddev().unwrap(), Some(time_unit));389+ let stddev_str = measurements.stddev().unwrap().format_auto(Some(time_unit));390 391 console_writeln!(392 stdout,393 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",96 unmodified linesmodified:src/export/csv.rs+1 added-2 removed
3 unmodified lines4 5 use super::Exporter;6 use crate::benchmark::benchmark_result::BenchmarkResult;7 use crate::options::SortOrder;8-use crate::quantity::{second, TimeQuantity};9-use crate::util::units::TimeUnit;8+use crate::quantity::{second, TimeQuantity, TimeUnit};9 10 use anyhow::Result;11 12 #[derive(Default)]169 unmodified linesmodified:src/export/json.rs+1 added-1 removed
2 unmodified lines3 4 use super::Exporter;5 use crate::benchmark::benchmark_result::BenchmarkResult;6 use crate::options::SortOrder;7-use crate::util::units::TimeUnit;7+use crate::quantity::TimeUnit;8 9 use anyhow::Result;10 11 #[derive(Serialize, Debug)]23 unmodified linesmodified:src/export/markup.rs+9 added-3 removed
49 unmodified lines50 for entry in entries {51 let result = &entry.result;52 // prepare data row strings53 let cmd_str = result.command_with_unused_parameters().replace('|', "\\|");54- let mean_str = format_duration_value(result.mean_wall_clock_time(), Some(time_unit)).0;54+ let mean_str = result55+ .mean_wall_clock_time()56+ .format_value_auto(Some(time_unit))57+ .0;58 let stddev_str = if let Some(stddev) = result.measurements.stddev() {56- format!(" ± {}", format_duration_value(stddev, Some(time_unit)).0)59+ format!(" ± {}", stddev.format_value_auto(Some(time_unit)).0)60 } else {61 "".into()62 };63 let min_str = result.measurements.min().format_value(time_unit);52 unmodified lines116 117 fn determine_unit_from_results(results: &[BenchmarkResult]) -> TimeUnit {118 if let Some(first_result) = results.first() {119 // Use the first BenchmarkResult entry to determine the unit for all entries.117- format_duration_value(first_result.mean_wall_clock_time(), None).1120+ first_result121+ .mean_wall_clock_time()122+ .format_auto_with_unit(None)123+ .1124 } else {125 // Default to `Second`.126 TimeUnit::Second127 }25 unmodified linesmodified:src/export/mod.rs+1 added-1 removed
16 unmodified lines17 use self::orgmode::OrgmodeExporter;18 19 use crate::benchmark::benchmark_result::BenchmarkResult;20 use crate::options::SortOrder;21-use crate::util::units::TimeUnit;21+use crate::quantity::TimeUnit;22 23 use anyhow::{Context, Result};24 use clap::ArgMatches;25 150 unmodified linesmodified:src/export/tests.rs+1 added-2 removed
1 unmodified line2 use crate::benchmark::benchmark_result::BenchmarkResult;3 use crate::benchmark::measurement::{Measurement, Measurements};4 use crate::export::asciidoc::AsciidocExporter;5 use crate::export::orgmode::OrgmodeExporter;6-use crate::quantity::{byte, second, Information, Time, TimeQuantity};7-use crate::util::units::TimeUnit;6+use crate::quantity::{byte, second, Information, Time, TimeQuantity, TimeUnit};7 use crate::{export::markdown::MarkdownExporter, options::SortOrder};8 use std::collections::BTreeMap;9 use std::process::ExitStatus;10 407 unmodified linesmodified:src/output/warnings.rs+3 added-4 removed
1 use std::fmt;2 3 use crate::benchmark::MIN_EXECUTION_TIME;4-use crate::output::format::format_duration;5-use crate::quantity::{millisecond, Time, TimeQuantity};4+use crate::quantity::{Time, TimeQuantity, TimeUnit};5 6 pub struct OutlierWarningOptions {7 pub warmup_in_use: bool,8 pub prepare_in_use: bool,15 unmodified lines24 "Command took less than {min_execution_time} 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.",29- min_execution_time = MIN_EXECUTION_TIME.to_string(millisecond)28+ min_execution_time = MIN_EXECUTION_TIME.format_value_in(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}",37- time=time_first_run.format_auto(),36+ time=time_first_run.format_auto(None),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+186 added-107 removed
1+use core::f64;2 use std::marker::PhantomData;3 3-use uom::si;4+use serde::ser::SerializeStruct;5+use serde::Serializer;6+use uom::{si, Conversion};7 8+pub use uom::si::information::{byte, kibibyte};9+pub use uom::si::ratio::ratio;10+pub use uom::si::time::{hour, microsecond, millisecond, minute, nanosecond, second};11+12+pub use si::f64::Ratio;13+pub use si::f64::Time;14+pub use si::u64::Information;15+16 pub use si::f64::{Information, Ratio, Time};17 pub use si::information::{byte, gibibyte, kibibyte, mebibyte, tebibyte};18 pub use si::ratio::ratio;19 pub use si::time::{hour, microsecond, millisecond, minute, nanosecond, second};20 pub use uom::num_traits::Zero;21 22 pub use units::{InformationUnit, IsUnit, TimeUnit};23 13-pub mod statistics;24 mod units;25 16-pub trait FormatQuantity {17- type Unit;26+pub trait TimeQuantity {27+ fn zero() -> Time {28+ Time::new::<second>(0.0)29+ }30 19- fn suitable_unit(&self) -> Self::Unit;31+ fn value_in<U>(&self, u: U) -> f6432+ where33+ U: si::time::Unit + Conversion<f64, T = f64>;34 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;35+ fn format_value_in(&self, time_unit: TimeUnit, precision: usize) -> String;36+ fn format_auto(&self, time_unit: Option<TimeUnit>) -> String;37+ fn format_auto_with_unit(&self, time_unit: Option<TimeUnit>) -> (String, TimeUnit);38+ fn format_value_auto(&self, time_unit: Option<TimeUnit>) -> (String, TimeUnit);39 }40 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- }41+impl TimeQuantity for Time {42+ fn value_in<U>(&self, _u: U) -> f6443+ where44+ U: si::time::Unit + Conversion<f64, T = f64>,45+ {46+ self.get::<U>()47 }48 40- /// Format the time duration in the given unit with the given precision.41- fn format_with_precision(&self, u: TimeUnit, precision: usize) -> String {49+ fn format_value_in(&self, u: TimeUnit, precision: usize) -> String {50 u.format(*self, precision)51 }52 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())53+ /// Format the given duration as a string. The output-unit can be enforced by setting `unit` to54+ /// `Some(target_unit)`. If `unit` is `None`, it will be determined automatically.55+ fn format_auto(&self, time_unit: Option<TimeUnit>) -> String {56+ self.format_auto_with_unit(time_unit).057 }58 51- /// Format the given time duration. The unit will be determined automatically.52- fn format_auto(&self) -> String {53- self.format(self.suitable_unit())59+ /// Like `format_duration`, but returns the target unit as well.60+ fn format_auto_with_unit(&self, time_unit: Option<TimeUnit>) -> (String, TimeUnit) {61+ let (out_str, out_unit) = self.format_value_auto(time_unit);62+63+ (format!("{} {}", out_str, out_unit.short_name()), out_unit)64 }65 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())66+ /// Like `format_duration`, but returns the target unit as well.67+ fn format_value_auto(&self, time_unit: Option<TimeUnit>) -> (String, TimeUnit) {68+ let (time_unit, precision) = if (*self < Time::new::<millisecond>(1.0)69+ && time_unit.is_none())70+ || time_unit == Some(TimeUnit::MicroSecond)71+ {72+ (TimeUnit::MicroSecond, 1)73+ } else if (*self < Time::new::<second>(1.0) && time_unit.is_none())74+ || time_unit == Some(TimeUnit::MilliSecond)75+ {76+ (TimeUnit::MilliSecond, 1)77+ } else {78+ let time_unit = time_unit.unwrap_or(TimeUnit::Second);79+ let precision = if time_unit == TimeUnit::Second { 3 } else { 1 };80+81+ (time_unit, precision)82+ };83+84+ (self.format_value_in(time_unit, precision), time_unit)85 }86 }87 88 pub const fn const_time_from_seconds(value: f64) -> Time {4 unmodified lines93 value,94 }95 }96 71-impl FormatQuantity for Information {72- type Unit = InformationUnit;73-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- }97+pub trait InformationQuantity {98+ fn zero() -> Information {99+ Information::new::<byte>(0)100 }101 86- /// Format the information in the given unit with the given precision.87- fn format_with_precision(&self, u: InformationUnit, precision: usize) -> String {88- u.format(*self, precision)89- }102+ fn value_in<U>(&self, u: U) -> u64103+ where104+ U: si::information::Unit + Conversion<u64, T = uom::num_rational::Ratio<u64>>;105 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- }106+ fn to_string<U>(&self, u: U) -> String107+ where108+ U: si::information::Unit + Conversion<u64, T = uom::num_rational::Ratio<u64>>;109+}110 97- /// Format the given information. The unit will be determined automatically.98- fn format_auto(&self) -> String {99- self.format(self.suitable_unit())111+impl InformationQuantity for Information {112+ fn value_in<U>(&self, _u: U) -> u64113+ where114+ U: si::information::Unit + Conversion<u64, T = uom::num_rational::Ratio<u64>>,115+ {116+ self.get::<U>()117 }118 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())119+ fn to_string<U>(&self, u: U) -> String120+ where121+ U: si::information::Unit + Conversion<u64, T = uom::num_rational::Ratio<u64>>,122+ {123+ format!(124+ "{}",125+ self.into_format_args(u, uom::fmt::DisplayStyle::Abbreviation)126+ )127 }128 }129 130+pub fn serialize_time<S>(t: &Time, s: S) -> Result<S::Ok, S::Error>131+where132+ S: Serializer,133+{134+ let mut state = s.serialize_struct("Time", 3)?;135+ state.serialize_field("value", &t.value)?;136+ state.serialize_field("unit", "second")?;137+ state.end()138+}139+140+pub fn serialize_information<S>(i: &Information, s: S) -> Result<S::Ok, S::Error>141+where142+ S: Serializer,143+{144+ let mut state = s.serialize_struct("Information", 3)?;145+ state.serialize_field("value", &i.value)?;146+ state.serialize_field("unit", "byte")?;147+ state.end()148+}149+150+macro_rules! quantity_fn {151+ ($name:ident, $unwrapped_values:ident, $body:expr) => {152+ pub fn $name(values: &[Time]) -> Time {153+ let $unwrapped_values: Vec<_> = values.iter().map(|q| q.value_in(second)).collect();154+ let result_value = $body;155+156+ Time::new::<second>(result_value)157+ }158+ };159+}160+161+quantity_fn!(mean, values, statistical::mean(&values));162+quantity_fn!(median, values, statistical::median(&values));163+quantity_fn!(min, values, crate::util::min_max::min(&values));164+quantity_fn!(max, values, crate::util::min_max::max(&values));165+quantity_fn!(standard_deviation, values, {166+ let mean_value = statistical::mean(&values);167+ statistical::standard_deviation(&values, Some(mean_value))168+});169+170 #[test]171 fn test_time() {172 let time = Time::new::<millisecond>(123.4);111- assert_eq!(time.get::<millisecond>(), 123.4);173+ assert_eq!(time.value_in(millisecond), 123.4);174 113- let time_s = time.get::<second>();175+ let time_s = time.value_in(second);176 approx::assert_relative_eq!(time_s, 0.1234);177 116- let time_us = time.get::<microsecond>();178+ let time_us = time.value_in(microsecond);179 approx::assert_relative_eq!(time_us, 123400.0);180 }181 182 #[test]183 fn test_information() {122- use uom::si::information::pebibyte;184+ let information = Information::new::<kibibyte>(8);185+ assert_eq!(information.value_in(byte), 8192);186 124- let information = Information::new::<kibibyte>(8.);125- assert_eq!(information.get::<byte>(), 8192.);187+ let information_kib = information.value_in(kibibyte);188+ assert_eq!(information_kib, 8);189+}190 127- let information_kib = information.get::<kibibyte>();128- assert_eq!(information_kib, 8.);191+#[test]192+fn test_format() {193+ let time = Time::new::<millisecond>(123.4);194+ assert_eq!(time.format_auto(Some(TimeUnit::Second)), "0.123 s");195+ assert_eq!(time.format_auto(Some(TimeUnit::MilliSecond)), "123.4 ms");196+ assert_eq!(time.format_auto(Some(TimeUnit::MicroSecond)), "123400.0 µs");197 130- let largest_exactly_representable = Information::new::<byte>(9_007_199_254_740_992.);131- assert_eq!(largest_exactly_representable.get::<pebibyte>(), 8.);198+ let peak_memory_usage = Information::new::<kibibyte>(8);199+ assert_eq!(peak_memory_usage.to_string(byte), "8192 B");200+ assert_eq!(peak_memory_usage.to_string(kibibyte), "8 KiB");201 }202 203 #[test]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- );204+fn test_mean() {205+ let values = vec![206+ Time::new::<millisecond>(123.4),207+ Time::new::<millisecond>(234.5),208+ ];209+ let result = mean(&values);210+ assert_eq!(result.format_auto(Some(TimeUnit::MilliSecond)), "178.9 ms");211 }212 213 #[test]214+fn test_format_duration() {215+ let (out_str, out_unit) = Time::new::<second>(1.3).format_auto_with_unit(None);216+217+#[test]218 fn test_suitable_unit_information() {219 assert_eq!(220 Information::new::<byte>(512.0).suitable_unit(),221 InformationUnit::Byte11 unmodified lines233 InformationUnit::GibiByte234 );235 }236 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");237+ let (out_str, out_unit) = Time::new::<second>(1.0).format_auto_with_unit(None);238 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- );239+ assert_eq!("1.000 s", out_str);240+ assert_eq!(TimeUnit::Second, out_unit);241+242+ let (out_str, out_unit) = Time::new::<second>(0.999).format_auto_with_unit(None);243+244+ assert_eq!("999.0 ms", out_str);245+ assert_eq!(TimeUnit::MilliSecond, out_unit);246+247+ let (out_str, out_unit) = Time::new::<second>(0.0005).format_auto_with_unit(None);248+249+ assert_eq!("500.0 µs", out_str);250+ assert_eq!(TimeUnit::MicroSecond, out_unit);251+252+ let (out_str, out_unit) = Time::new::<second>(0.).format_auto_with_unit(None);253+254+ assert_eq!("0.0 µs", out_str);255+ assert_eq!(TimeUnit::MicroSecond, out_unit);256+257+ let (out_str, out_unit) = Time::new::<second>(1000.0).format_auto_with_unit(None);258+259+ assert_eq!("1000.000 s", out_str);260+ assert_eq!(TimeUnit::Second, out_unit);261 }262 263 #[test]264 fn test_format_duration_unit_with_unit() {195- let out = Time::new::<second>(1.3).format(TimeUnit::Second);196- assert_eq!("1.300 s", out);265+ let (out_str, out_unit) =266+ Time::new::<second>(1.3).format_auto_with_unit(Some(TimeUnit::Second));267 268 let out = Time::new::<second>(1.3).format(TimeUnit::MilliSecond);269 assert_eq!("1300.0 ms", out);270 201- let out = Time::new::<second>(1.3).format(TimeUnit::MicroSecond);202- assert_eq!("1300000.0 µs", out);271+ let (out_str, out_unit) =272+ Time::new::<second>(1.3).format_auto_with_unit(Some(TimeUnit::MilliSecond));273+274+ assert_eq!("1300.0 ms", out_str);275+ assert_eq!(TimeUnit::MilliSecond, out_unit);276+277+ let (out_str, out_unit) =278+ Time::new::<second>(1.3).format_auto_with_unit(Some(TimeUnit::MicroSecond));279+280+ assert_eq!("1300000.0 µs", out_str);281+ assert_eq!(TimeUnit::MicroSecond, out_unit);282 }modified:src/quantity/units.rs+43 added-30 removed
21 unmodified lines22 self.dispatch().format_value(value, precision)23 }24 }25 26+use std::marker::PhantomData;27+28+use crate::quantity::{hour, microsecond, millisecond, minute, second, Time};29+30 /// Supported time units31 #[derive(Debug, Clone, Copy, PartialEq, Eq)]32 pub enum TimeUnit {33 MicroSecond,2 unmodified lines36 Minute,37 Hour,38 }39 36-impl IsUnit for TimeUnit {37- type Quantity = Time;40+struct Dispatcher<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> {41+ u: PhantomData<U>,42+}43 39- fn dispatch(&self) -> Box<dyn UnitImpl<Quantity = Time>> {40- match self {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- }44+impl<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> Dispatcher<U> {45+ fn new() -> Self {46+ Dispatcher { u: PhantomData }47 }48+}49 49- fn preferred_precision(&self) -> usize {50+trait UnitImpl {51+ fn short_name(&self) -> &'static str;52+ fn format_value(&self, value: Time, precision: usize) -> String;53+}54+55+impl<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> UnitImpl for Dispatcher<U> {56+ fn short_name(&self) -> &'static str {57+ U::abbreviation()58+ }59+60+ fn format_value(&self, value: Time, precision: usize) -> String {61+ format!("{value:.precision$}", value = value.get::<U>())62+ }63+}64+65+impl TimeUnit {66+ fn dispatch(self) -> Box<dyn UnitImpl> {67 match self {51- TimeUnit::Second => 3,52- _ => 1,68+ TimeUnit::MicroSecond => Box::new(Dispatcher::<microsecond>::new()),69+ TimeUnit::MilliSecond => Box::new(Dispatcher::<millisecond>::new()),70+ TimeUnit::Second => Box::new(Dispatcher::<second>::new()),71+ TimeUnit::Minute => Box::new(Dispatcher::<minute>::new()),72+ TimeUnit::Hour => Box::new(Dispatcher::<hour>::new()),73 }74 }75+76+ /// A short abbreviation like `s`, `ms`, or `µs`.77+ pub fn short_name(self) -> &'static str {78+ self.dispatch().short_name()79+ }80+81+ /// Formats the quantity as a string in the given Unit.82+ pub fn format(self, value: Time, precision: usize) -> String {83+ self.dispatch().format_value(value, precision)84+ }85 }86 87 /// Supported information units88 #[derive(Debug, Clone, Copy, PartialEq, Eq)]87 unmodified lines176 assert_eq!("µs", TimeUnit::MicroSecond.short_name());177 assert_eq!("min", TimeUnit::Minute.short_name());178 assert_eq!("h", TimeUnit::Hour.short_name());179 }150-151-// Note - the values are rounded when formatted.152-#[test]153-fn test_unit_format() {154- use crate::quantity::FormatQuantity;155-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/options.rs+1 added-2 removed
7 unmodified lines8 use clap::ArgMatches;9 10 use crate::command::Commands;11 use crate::error::OptionsError;12-use crate::quantity::{second, Time};13-use crate::util::units::TimeUnit;12+use crate::quantity::{second, Time, TimeUnit};13 14 use anyhow::Result;15 16 #[cfg(not(windows))]560 unmodified lines