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

不羁的心 提交于 2020-01-24 03:05:39

问题


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.


回答1:


Here is the solution I came up with, which is to multiply the seconds by a billion, add it to the nanoseconds, then divide by 1e6.

let nanos = timeout_duration.subsec_nanos() as u64;
let ms = (1000*1000*1000 * timeout_duration.as_secs() + nanos)/(1000 * 1000);



回答2:


Use time::Duration from the time crate on crates.io which provides a num_milliseconds() method.




回答3:


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?


来源:https://stackoverflow.com/questions/36816072/how-do-i-get-a-duration-as-a-number-of-milliseconds-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!