目录
一、用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.https://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