How can I get the current system epoch time in milliseconds/seconds (and to a lesser extent nanoseconds and microseconds) in Rust?
To get the current epoch time in Rust you can use SystemTime::now()
along with .duration_since
and UNIX_EPOCH
.
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
let now = SystemTime::now();
let duration_since_epoch = now.duration_since(UNIX_EPOCH).expect("Time before UNIX_EPOCH");
let nanos: u128 = duration_since_epoch.as_nanos();
let micros: u128 = duration_since_epoch.as_micros();
// These two are probably what most are looking for
let millis: u128 = duration_since_epoch.as_millis();
let secs: u64 = duration_since_epoch.as_secs();
println!("Epoch time in nanoseconds: {}, microseconds: {}, milliseconds: {}, seconds: {}", nanos, micros, millis, secs);
}
Also, if you are trying to measure elapsed time for benchmarking (or some similar use case), you may want to consider using Rust's Instant
over SystemTime
.