cpu temp windows in rust

To get the CPU temperature in Windows using Rust, you can use the following approaches:

Using the sysinfo Crate

You can use the sysinfo crate, which provides a cross-platform way to get system information, including CPU temperature. Here's an example:

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

fn main() {
    let s = System::new_all();
    let cpu_temp = s.get_components().into_iter().find_map(|c| match c {
        sysinfo::Component::Cpu(c) => Some(c.temperature()),
        _ => None,
    });

    match cpu_temp {
        Some(temp) => println!("CPU Temperature: {}°C", temp),
        None => println!("Failed to get CPU temperature"),
    }
}
391 chars
15 lines

Add the following dependency to your Cargo.toml file:

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

Using the wmi Crate

Alternatively, you can use the wmi crate, which allows you to query WMI (Windows Management Instrumentation) classes to get system information. Here's an example:

main.rs
use wmi::{WMI, WMIClass};

fn main() {
    let wmi = WMI::new();
    let temp_info = wmi.query(
        "SELECT * FROM Win32_TemperatureProbe",
        |record| {
            let temperature = record.get("CurrentTemperature").unwrap();
            println!("CPU Temperature: {}°C", temperature);
        },
    ).unwrap();

    if temp_info.count() == 0 {
        println!("Failed to get CPU temperature");
    }
}
415 chars
17 lines

Add the following dependency to your Cargo.toml file:

[dependencies]
wmi = "0.4.0"
29 chars
3 lines

Note: The wmi crate requires the winapi feature to be enabled. You can do this by adding the following line to your Cargo.toml file:

[features]
default = ["winapi"]
32 chars
3 lines

Using the kernel32 Crate

You can also use the kernel32 crate to call the Windows API function GetProcessTimes to get the CPU temperature. However, this method is more complex and requires manual error handling.

main.rs
use kernel32::{GetProcessTimes, FILETIME};
use winbase::FILETIME_TO_SYSTEMTIME;

fn main() {
    let mut creation_time = FILETIME::default();
    let mut exit_time = FILETIME::default();
    let mut kernel_time = FILETIME::default();
    let mut user_time = FILETIME::default();

    unsafe {
        GetProcessTimes(
            std::process::id() as winapi::shared::minwindef::DWORD,
            &mut creation_time,
            &mut exit_time,
            &mut kernel_time,
            &mut user_time,
        );
    }

    let system_time = FILETIME_TO_SYSTEMTIME(kernel_time);
    println!("CPU Temperature: {}°C", system_time.wYear);
}
641 chars
23 lines

Add the following dependency to your Cargo.toml file:

[dependencies]
kernel32 = "0.2.83"
winbase = "0.2.0"
winapi = "0.3.9"
70 chars
5 lines

related categories

gistlibby LogSnag