Loading…

To see CPU consumption per process on Linux from a Rust program, use the sysinfo crate. It reads /proc, compares two samples, and reports a CPU percentage for every process. This guide gives a working program, explains the output, and fixes the most common wrong readings.

What You Need

  • A Linux server (any distribution) with a recent stable Rust toolchain. Current sysinfo releases need a recent compiler; run rustup update if the build reports an unsupported rustc version.
  • Root access is normally not required to read process data.

Step 1: Create the Project

cargo new process-cpu && cd process-cpu
cargo add sysinfo

Step 2: Add the Code

Replace src/main.rs with:

use std::{thread, time::Duration};
use sysinfo::{ProcessesToUpdate, System, MINIMUM_CPU_UPDATE_INTERVAL};

fn main() {
    let mut sys = System::new();

    // First refresh stores a baseline; CPU % is 0.0 until the second refresh.
    sys.refresh_processes(ProcessesToUpdate::All, true);
    thread::sleep(MINIMUM_CPU_UPDATE_INTERVAL.max(Duration::from_millis(500)));
    sys.refresh_processes(ProcessesToUpdate::All, true);

    let cores = thread::available_parallelism().map(|n| n.get()).unwrap_or(1) as f32;
    let mut procs: Vec<_> = sys.processes().values().collect();
    procs.sort_by(|a, b| b.cpu_usage().total_cmp(&a.cpu_usage()));

    println!("{:>8} {:>8} {:>9}  NAME", "PID", "CPU %", "% OF ALL");
    for p in procs.iter().take(10) {
        println!(
            "{:>8} {:>8.1} {:>9.1}  {}",
            p.pid(),
            p.cpu_usage(),
            p.cpu_usage() / cores,
            p.name().to_string_lossy()
        );
    }
}

CPU usage is calculated from process time over an interval, so each process must be refreshed twice with a short pause between samples.

Step 3: Run and Read the Output

cargo run --release

Example output with one busy process on a single-vCPU server:

     PID    CPU %  % OF ALL  NAME
    636    100.0     100.0  yes
    638      2.0       2.0  cpuproc

  • CPU % uses a per-core scale. 100 means one full core, and the value can exceed 100 on multi-core servers.
  • % OF ALL divides that value by the core count, giving each process's share of the whole machine (0–100).

Troubleshooting Wrong or Missing Values

SymptomCauseFix 
Every value is 0.0Only one refresh, or the pause was too shortRefresh twice, waiting at least MINIMUM_CPU_UPDATE_INTERVAL (200 ms on Linux) between refreshes
Values above 100%Normal on multi-core systemsDivide by the core count
Values reset to 0.0 in a loopA new System is created on every passCreate System once and keep refreshing it
Other users' processes are missing/proc may be mounted with hidepid, or you are inside a containerCheck mount | grep ' /proc '; run as root if appropriate. Containers only see their own processes

For continuous monitoring, keep one System, refresh it every one to two seconds, and read cpu_usage() after each refresh.

Alternative: Read /proc Directly (No Crate)

Linux exposes per-process CPU time in /proc/<pid>/stat. Field 14 (utime) and field 15 (stime) are measured in clock ticks; divide by sysconf(_SC_CLK_TCK) to get seconds.

  1. Read utime + stime for a PID.
  2. Wait a known interval, then read it again.
  3. Compute: CPU % = (tick delta ÷ ticks per second) ÷ elapsed seconds × 100.

The second field, the command name, is in parentheses and may contain spaces, so parse the fields after the last ).

Verify the Results

Compare your program with top. Run top -b -n 2 -d 1 | head -n 20 and use the second screen, because the first screen is not a reliable interval measurement. Avoid comparing with ps -eo pid,pcpu,comm --sort=-pcpu, as its %CPU is an average over the process's lifetime, so it will differ from your interval-based numbers.

If a legitimate workload keeps CPU saturated, add vCPUs on an ICSDC VPS or move heavy workloads to a Linux dedicated server.