Files
hyperfine/src/util/units.rs
T

61 lines
1.8 KiB
Rust
Raw Normal View History

2021-08-24 21:33:48 +02:00
//! This module contains common units.
2019-06-08 11:47:50 +02:00
pub type Scalar = f64;
/// Type alias for unit of time
2019-06-08 11:47:50 +02:00
pub type Second = Scalar;
/// Supported time units
2022-09-07 09:20:50 +02:00
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unit {
Second,
MilliSecond,
2023-10-05 09:39:00 +02:00
MicroSecond,
Minute,
Hour,
}
impl Unit {
/// The abbreviation of the Unit.
2019-07-13 10:38:51 +02:00
pub fn short_name(self) -> String {
match self {
Unit::Second => String::from("s"),
Unit::MilliSecond => String::from("ms"),
2023-10-05 09:39:00 +02:00
Unit::MicroSecond => String::from("µs"),
Unit::Minute => String::from("min"),
Unit::Hour => String::from("h"),
}
}
/// Returns the Second value formatted for the Unit.
2019-07-13 10:38:51 +02:00
pub fn format(self, value: Second) -> String {
match self {
2024-05-31 13:26:35 -07:00
Unit::Second => format!("{value:.3}"),
Unit::MilliSecond => format!("{:.1}", value * 1e3),
2023-10-05 09:39:00 +02:00
Unit::MicroSecond => format!("{:.1}", value * 1e6),
Unit::Minute => format!("{:.1}", value / 60.0),
Unit::Hour => format!("{:.1}", value / 3600.0),
}
}
}
#[test]
fn test_unit_short_name() {
assert_eq!("s", Unit::Second.short_name());
assert_eq!("ms", Unit::MilliSecond.short_name());
2023-10-05 09:39:00 +02:00
assert_eq!("µs", Unit::MicroSecond.short_name());
assert_eq!("min", Unit::Minute.short_name());
assert_eq!("h", Unit::Hour.short_name());
}
// Note - the values are rounded when formatted.
#[test]
fn test_unit_format() {
let value: Second = 123.456789;
assert_eq!("123.457", Unit::Second.format(value));
assert_eq!("123456.8", Unit::MilliSecond.format(value));
2023-10-05 09:39:00 +02:00
assert_eq!("1234.6", Unit::MicroSecond.format(0.00123456));
assert_eq!("2.1", Unit::Minute.format(value));
assert_eq!("0.0", Unit::Hour.format(value));
}