如何用Rust获取CPU、内存、硬盘的信息?

发布于:2024-05-18 ⋅ 阅读:(273) ⋅ 点赞:(0)

目录

一、用Rust获取CPU、内存、硬盘的信息

二、知识点 systemstat


一、用Rust获取CPU、内存、硬盘的信息

        首先,需要添加systemstat库到Cargo.toml文件:

[dependencies]
systemstat = "0.2.3"

        在Rust代码中使用它: 

extern crate systemstat;

use std::io;
use std::thread;
use std::time::Duration;
use systemstat::{System, Platform, saturating_sub_bytes};

fn main() -> io::Result<()> {

    let sys = System::new();

    match sys.cpu_load_aggregate() {
        Ok(cpu)=> {
            println!("\nMeasuring CPU load...");
            thread::sleep(Duration::from_secs(5));
            let cpu = cpu.done().unwrap();
            println!("CPU load: {}% user, {}% nice, {}% system, {}% intr, {}% idle ",
                     cpu.user * 100.0, cpu.nice * 100.0, cpu.system * 100.0, cpu.interrupt * 100.0, cpu.idle * 100.0);
        },
        Err(x) => println!("\nCPU load: error: {}", x)
    }

    match sys.memory() {
        Ok(mem) => println!("\nMemory: {} used / {} ({} bytes) total ({:?})", saturating_sub_bytes(mem.total, mem.free), mem.total, mem.total.as_u64(), mem.platform_memory),
        Err(x) => println!("\nMemory: error: {}", x)
    }

    match sys.mounts() {
        Ok(mounts) => {
            println!("\nMounts:");
            for mount in mounts.iter() {
                println!("{} ---{}---> {} (available {} of {})",
                         mount.fs_mounted_from, mount.fs_type, mount.fs_mounted_on, mount.avail, mount.total);
            }
        }
        Err(x) => println!("\nMounts: error: {}", x)
    }

    Ok(())
}

显示结果:

二、知识点 systemstat

systemstat - RustThis library provides a way to access system information such as CPU load, mounted filesystems, network interfaces, etc.icon-default.png?t=N7T8https://docs.rs/systemstat/latest/systemstat/

GitHub - valpackett/systemstat: Rust library for getting system information | also on https://codeberg.org/valpackett/systemstat

systemstat

A Rust library for getting system information/statistics:

  • CPU load
  • load average
  • memory usage
  • uptime / boot time
  • battery life
  • filesystem mounts (and disk usage)
  • disk I/O statistics
  • network interfaces
  • network traffic statistics
  • CPU temperature

Unlike sys-info-rs, this one is written purely in Rust.

Supported platforms (roughly ordered by completeness of support):

  • FreeBSD
  • Linux
  • OpenBSD
  • Windows
  • macOS
  • NetBSD
  • more coming soon

网站公告

今日签到

点亮在社区的每一天
去签到