gpu temp in rust in rust

To get the GPU temperature in Rust, you can use the following approaches:

Using the nvidia-smi command

You can use the std::process::Command to execute the nvidia-smi command and parse the output to get the GPU temperature.

main.rs
use std::process::Command;

fn get_gpu_temp() -> String {
    let output = Command::new("nvidia-smi")
        .arg("--query-gpu=name,temperature.gpu")
        .arg("--format=csv")
        .output()
        .expect("failed to execute command");

    let output_str = String::from_utf8(output.stdout).expect("failed to parse output");
    let lines: Vec<&str> = output_str.lines().collect();

    lines[1].to_string()
}

fn main() {
    println!("{}", get_gpu_temp());
}
469 chars
19 lines

Using the sysfs filesystem

On Linux systems, you can use the sysfs filesystem to get the GPU temperature.

main.rs
use std::fs;
use std::path::Path;

fn get_gpu_temp() -> String {
    let path = Path::new("/sys/class/drm/card0/device/hwmon/hwmon0/temp1_input");
    let temp_str = fs::read_to_string(path).expect("failed to read temperature");
    let temp: f64 = temp_str.trim().parse().expect("failed to parse temperature");

    format!("{:.2}°C", temp / 1000.0)
}

fn main() {
    println!("{}", get_gpu_temp());
}
404 chars
15 lines

Using a Rust library

There are several Rust libraries available that provide a convenient API to get the GPU temperature, such as gpu-temperature and nvidia-smi-rs.

main.rs
use gpu_temperature::Temperature;

fn get_gpu_temp() -> String {
    let temp = Temperature::new().expect("failed to create temperature object");
    let gpu_temp = temp.get_gpu_temp().expect("failed to get gpu temperature");

    format!("{:.2}°C", gpu_temp)
}

fn main() {
    println!("{}", get_gpu_temp());
}
313 chars
13 lines

Note: The above examples are just a starting point, and you may need to modify them to suit your specific use case. Additionally, the nvidia-smi command and sysfs filesystem approaches may require root privileges to access the GPU temperature.

related categories

gistlibby LogSnag