use std::time::Duration;
const NS_PER_US: u128 = 1_000;
const NS_PER_MS: u128 = 1_000_000;
const NS_PER_S: u128 = 1_000_000_000;
const NS_PER_MIN: u128 = 60 * NS_PER_S;
const NS_PER_H: u128 = 60 * NS_PER_MIN;
#[inline]
pub fn format_duration(duration: Duration, round: Option<u8>) -> String {
let precision = round.unwrap_or(2).min(9) as usize; let total_ns = duration.as_nanos();
let (unit_value, unit_name, divisor) = if total_ns < NS_PER_US {
(total_ns, "ns", 1)
} else if total_ns < NS_PER_MS {
(total_ns, "μs", NS_PER_US)
} else if total_ns < NS_PER_S {
(total_ns, "ms", NS_PER_MS)
} else if total_ns < NS_PER_MIN {
(total_ns, "s", NS_PER_S)
} else if total_ns < NS_PER_H {
(total_ns, "min", NS_PER_MIN)
} else {
(total_ns, "h", NS_PER_H)
};
let integer_part = unit_value / divisor;
let remainder = unit_value % divisor;
if remainder == 0 && precision == 0 {
format!("{}{}", integer_part, unit_name)
} else {
let scale = 10u128.pow(precision as u32);
let fractional = (remainder * scale) / divisor;
format!(
"{}.{:0width$}{}",
integer_part,
fractional,
unit_name,
width = precision
)
}
}
pub fn format_better_duration(duration: Duration) -> String {
let sec = duration.as_secs();
let min = sec / 60;
let h = min / 60;
if h > 0 {
return format!("{:02}h {:02}m {:02}s", h, min, sec);
} else if min > 0 {
return format!("{:02}m {:02}s", min, sec);
}
let ms = duration.subsec_millis();
format!("{:02}s {:03}ms", sec, ms)
}