Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a Duration as a number of milliseconds in Rust

Tags:

rust

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.

like image 676
Kevin Burke Avatar asked Apr 23 '16 20:04

Kevin Burke


People also ask

How do you get a timestamp in Rust?

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.

How long is a millisecond?

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.


1 Answers

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:

  • How can I get the current time in milliseconds?
like image 79
iceqing Avatar answered Sep 18 '22 04:09

iceqing