I have a time::Duration
. How can I get the number of milliseconds represented by this duration as an integer? There used to be a num_milliseconds()
function, but it is no longer available.
In Rust we have time::get_time() which returns a Timespec with the current time as seconds and the offset in nanoseconds since midnight, January 1, 1970.
A millisecond (ms or msec) is one thousandth of a second and is commonly used in measuring the time to read to or write from a hard disk or a CD-ROM player or to measure packet travel time on the Internet. For comparison, a microsecond (us or Greek letter mu plus s) is one millionth (10-6) of a second.
Since Rust 1.33.0, there is an as_millis()
function:
use std::time::SystemTime;
fn main() {
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("get millis error");
println!("now millis: {}", now.as_millis());
}
Since Rust 1.27.0, there is a subsec_millis()
function:
use std::time::SystemTime;
fn main() {
let since_the_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("get millis error");
let seconds = since_the_epoch.as_secs();
let subsec_millis = since_the_epoch.subsec_millis() as u64;
println!("now millis: {}", seconds * 1000 + subsec_millis);
}
Since Rust 1.8, there is a subsec_nanos
function:
let in_ms = since_the_epoch.as_secs() * 1000 +
since_the_epoch.subsec_nanos() as u64 / 1_000_000;
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With