Skip to content

Commit

Permalink
further optimize uptime retrival
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
NotAShelf committed Jan 25, 2025
1 parent 592fb58 commit d0f88b1
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions src/uptime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 uptime_seconds = info.uptime().as_secs();

let total_minutes = uptime_seconds / 60;
let days = total_minutes / (60 * 24);
let hours = (total_minutes % (60 * 24)) / 60;
let minutes = total_minutes % 60;
let days = uptime_seconds / (60 * 60 * 24);
let hours = (uptime_seconds / 3600) % 24;
let minutes = (uptime_seconds / 60) % 60;

let parts = [(days, "day"), (hours, "hour"), (minutes, "minute")]
.iter()
.filter(|&&(value, _)| value > 0)
.map(|&(value, label)| format!("{value} {label}{}", if value > 1 { "s" } else { "" }))
.collect::<Vec<_>>();
let mut result = String::new();
if days > 0 {
result.push_str(&format!("{days} day{}", if days > 1 { "s" } else { "" }));
}
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)
}

0 comments on commit d0f88b1

Please sign in to comment.