get cpu temperature in rust

You can use the sysinfo crate in Rust to get the CPU temperature. Here's an example:

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

fn main() {
    let sys = System::new_all();
    let cpu_temp = sys.get_cpu_temp();
    match cpu_temp {
        Some(temp) => println!("CPU temperature: {}°C", temp),
        None => println!("CPU temperature not available"),
    }
}
270 chars
11 lines

Add the following dependency to your Cargo.toml:

[dependencies]
sysinfo = "0.23.5"
34 chars
3 lines

Note: The sysinfo crate may not work on all platforms, and the CPU temperature may not be available on all systems.

Alternatively, you can use the linux-thermal crate on Linux systems:

main.rs
use linux_thermal::{ThermalZone, ThermalZoneType};

fn main() {
    let zones = ThermalZone::get_all();
    for zone in zones {
        if zone.get_type() == ThermalZoneType::Cpu {
            println!("CPU temperature: {}°C", zone.get_temp());
        }
    }
}
263 chars
11 lines

Add the following dependency to your Cargo.toml:

[dependencies]
linux-thermal = "0.1.4"
39 chars
3 lines

This crate is specific to Linux and requires the thermal_zone kernel module to be loaded.

Please ensure to handle any potential errors that may arise when using these crates.

related categories

gistlibby LogSnag