itop/src/sysinfo_snapshot.rs
electria b20158820b
feat: process list
this is unnacceptably unperformant;
I think I've reached the point at which sysinfo doesn't do what I want,
which is keep track of a table of processes efficiently enough.
2026-08-18 14:11:01 -07:00

87 lines
2.3 KiB
Rust

use std::time::Duration;
pub fn refreshes() -> sysinfo::RefreshKind {
sysinfo::RefreshKind::nothing()
.with_memory(sysinfo::MemoryRefreshKind::everything())
.with_cpu(sysinfo::CpuRefreshKind::nothing().with_cpu_usage())
.with_processes(
sysinfo::ProcessRefreshKind::nothing()
.with_cpu()
.with_cmd(sysinfo::UpdateKind::OnlyIfNotSet)
.with_exe(sysinfo::UpdateKind::OnlyIfNotSet),
)
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct SysinfoSnapshot {
/// in seconds
uptime: u64,
pub cpu_total: f32,
pub cpus: Vec<f32>,
pub memory: u64,
pub memory_total: u64,
pub swap: u64,
pub swap_total: u64,
pub processes: Vec<ProcessSnapshot>,
}
impl SysinfoSnapshot {
#[cfg_attr(not(feature = "app"), allow(dead_code))]
pub fn uptime(&self) -> Duration {
Duration::from_secs(self.uptime)
}
}
impl From<&sysinfo::System> for SysinfoSnapshot {
fn from(value: &sysinfo::System) -> Self {
Self {
uptime: sysinfo::System::uptime(),
cpu_total: value.global_cpu_usage(),
cpus: value.cpus().iter().map(|cpu| cpu.cpu_usage()).collect(),
memory: value.used_memory(),
memory_total: value.total_memory(),
swap: value.used_swap(),
swap_total: value.total_swap(),
processes: value
.processes()
.iter()
.map(|(_pid, process)| ProcessSnapshot::from(process))
.collect(),
}
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ProcessSnapshot {
pub pid: usize,
/// in CPU-milliseconds
accumulated_cpu_time: u64,
/// note: it's by core, and can be up to eg 1600 on a 16-core device
pub cpu_usage: f32,
pub name: String,
}
impl ProcessSnapshot {
pub fn cpu_time(&self) -> Duration {
Duration::from_millis(self.accumulated_cpu_time)
}
}
impl From<&sysinfo::Process> for ProcessSnapshot {
fn from(value: &sysinfo::Process) -> Self {
Self {
pid: value.pid().into(),
accumulated_cpu_time: value.accumulated_cpu_time(),
cpu_usage: value.cpu_usage(),
name: value.name().to_string_lossy().into_owned(),
}
}
}