mirror of
https://github.com/NotAShelf/microfetch.git
synced 2025-02-06 04:03:17 +00:00
further optimize uptime retrival
Try and minimize expensive operations (e.g., divisions and allocations) to hopefully get a *consistent* measurable performance improvement. In my testing this brings the get_current function duration from > 1.2600 µs to < 1.2400 µs.
This commit is contained in:
parent
592fb58474
commit
d0f88b179c
1 changed files with 23 additions and 10 deletions
|
@ -5,16 +5,29 @@ pub fn get_current() -> Result<String, io::Error> {
|
||||||
let info = sysinfo().map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
let info = sysinfo().map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
||||||
let uptime_seconds = info.uptime().as_secs();
|
let uptime_seconds = info.uptime().as_secs();
|
||||||
|
|
||||||
let total_minutes = uptime_seconds / 60;
|
let days = uptime_seconds / (60 * 60 * 24);
|
||||||
let days = total_minutes / (60 * 24);
|
let hours = (uptime_seconds / 3600) % 24;
|
||||||
let hours = (total_minutes % (60 * 24)) / 60;
|
let minutes = (uptime_seconds / 60) % 60;
|
||||||
let minutes = total_minutes % 60;
|
|
||||||
|
|
||||||
let parts = [(days, "day"), (hours, "hour"), (minutes, "minute")]
|
let mut result = String::new();
|
||||||
.iter()
|
if days > 0 {
|
||||||
.filter(|&&(value, _)| value > 0)
|
result.push_str(&format!("{days} day{}", if days > 1 { "s" } else { "" }));
|
||||||
.map(|&(value, label)| format!("{value} {label}{}", if value > 1 { "s" } else { "" }))
|
}
|
||||||
.collect::<Vec<_>>();
|
if hours > 0 {
|
||||||
|
if !result.is_empty() {
|
||||||
|
result.push_str(", ");
|
||||||
|
}
|
||||||
|
result.push_str(&format!("{hours} hour{}", if hours > 1 { "s" } else { "" }));
|
||||||
|
}
|
||||||
|
if minutes > 0 {
|
||||||
|
if !result.is_empty() {
|
||||||
|
result.push_str(", ");
|
||||||
|
}
|
||||||
|
result.push_str(&format!(
|
||||||
|
"{minutes} minute{}",
|
||||||
|
if minutes > 1 { "s" } else { "" }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
Ok(parts.join(", "))
|
Ok(result)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue