get system cpu temperature in celsius in rust

To get the CPU temperature in Celsius in Rust, we can use the sysinfo crate which provides a platform-agnostic way to get system information. Here's how you do it:

  1. Add the sysinfo crate to your Cargo.toml file:
[dependencies]
sysinfo = "0.15.8"
34 chars
3 lines
  1. Import the SystemExt trait and create a new System instance:
main.rs
use sysinfo::{System, SystemExt};

fn main() {
    let system = System::new();
}
81 chars
6 lines
  1. Get the temperature of each Processor (i.e. CPU) and convert it to Celsius:
main.rs
let processor_temperatures: Vec<f32> = system.get_processors().iter().map(|p| p.get_temperature() as f32 / 1000.0).collect();
126 chars
2 lines

The get_temperature() method returns the temperature in millidegrees Celsius, so we divide it by 1000 to convert it to regular Celsius.

Here's the full code:

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

fn main() {
    let system = System::new();
    let processor_temperatures: Vec<f32> = system.get_processors().iter().map(|p| p.get_temperature() as f32 / 1000.0).collect();
    println!("{:?}", processor_temperatures);
}
257 chars
8 lines

gistlibby LogSnag