get system boot time in milliseconds in rust

To get the system boot time in millisecond resolution in Rust, we need to use system-programming to interact with the operating system to query for the boot time information. We can use the systemstat crate to achieve this.

First, add the systemstat crate to your Cargo.toml file:

[dependencies]
systemstat = "0.3.1"
36 chars
3 lines

Then, use the following code to get the system boot time in milliseconds:

main.rs
use systemstat::{Platform, System};

fn main() {
    let sys = System::new(); // create new System object
    match sys.boot_time() { // get boot time from System object
        Ok(boot_time) => {
            let millis_since_boot = boot_time.elapsed().unwrap().as_millis(); // get time since boot in milliseconds
            println!("System started {} milliseconds ago", millis_since_boot);
        }
        Err(x) => panic!("Error: {}", x),
    };
}
454 chars
13 lines

This code calls System::boot_time() function to retrieve the system boot time as a chrono::DateTime object. Using the elapsed() method on this object, it calculates the time elapsed since boot time and then calls as_millis() function to retrieve the elapsed time in milliseconds. Finally, it prints the elapsed time in milliseconds to the console.

gistlibby LogSnag