/ thirdparty / hyperfine / src / util / units.rs
units.rs
 1  //! This module contains common units.
 2  
 3  pub type Scalar = f64;
 4  
 5  /// Type alias for unit of time
 6  pub type Second = Scalar;
 7  
 8  /// Supported time units
 9  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
10  pub enum Unit {
11      Second,
12      MilliSecond,
13      MicroSecond,
14  }
15  
16  impl Unit {
17      /// The abbreviation of the Unit.
18      pub fn short_name(self) -> String {
19          match self {
20              Unit::Second => String::from("s"),
21              Unit::MilliSecond => String::from("ms"),
22              Unit::MicroSecond => String::from("µs"),
23          }
24      }
25  
26      /// Returns the Second value formatted for the Unit.
27      pub fn format(self, value: Second) -> String {
28          match self {
29              Unit::Second => format!("{value:.3}"),
30              Unit::MilliSecond => format!("{:.1}", value * 1e3),
31              Unit::MicroSecond => format!("{:.1}", value * 1e6),
32          }
33      }
34  }
35  
36  #[test]
37  fn test_unit_short_name() {
38      assert_eq!("s", Unit::Second.short_name());
39      assert_eq!("ms", Unit::MilliSecond.short_name());
40      assert_eq!("µs", Unit::MicroSecond.short_name());
41  }
42  
43  // Note - the values are rounded when formatted.
44  #[test]
45  fn test_unit_format() {
46      let value: Second = 123.456789;
47      assert_eq!("123.457", Unit::Second.format(value));
48      assert_eq!("123456.8", Unit::MilliSecond.format(value));
49  
50      assert_eq!("1234.6", Unit::MicroSecond.format(0.00123456));
51  }