get cpu load in rust

You can use the sysinfo crate in Rust to get the CPU load. Here's an example of how to do it:

main.rs
use sysinfo::{System, SystemExt};

fn main() {
    let s = System::new_all();
    let cpu_load = s.get_cpu_info().load_average();
    println!("CPU Load: {:?}", cpu_load);
}
174 chars
8 lines

You can also use the get_cpu_usage method to get the current CPU usage:

main.rs
use sysinfo::{System, SystemExt};

fn main() {
    let s = System::new_all();
    let cpu_usage = s.get_cpu_info().get_cpu_usage();
    println!("CPU Usage: {:?}", cpu_usage);
}
178 chars
8 lines

Make sure to add the sysinfo crate as a dependency in your Cargo.toml file:

[dependencies]
sysinfo = "0.23.10"
35 chars
3 lines

You can also use the std::thread and std::time modules to get the CPU load, but it's more complex and platform-dependent:

main.rs
use std::thread;
use std::time::Duration;

fn main() {
    loop {
        let start = std::time::Instant::now();
        let start_idle = std::time::Instant::now();
        thread::sleep(Duration::from_millis(100));
        let end = std::time::Instant::now();
        let end_idle = std::time::Instant::now();
        let cpu_usage = (end.duration_since(start) - end_idle.duration_since(start_idle)).as_millis() as f64 / end.duration_since(start).as_millis() as f64;
        println!("CPU Usage: {:.2}%", cpu_usage * 100.0);
        thread::sleep(Duration::from_millis(100));
    }
}
585 chars
16 lines

Note that this method is not as accurate as using the sysinfo crate and may not work on all platforms.

related categories

gistlibby LogSnag