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

目录

一、用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
  • 16
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值