Show used and free memory of the computer using Rust

refresh_all total_memory used_memory total_swap used_swap separate_with_commas

The sysinfo crate can provide a lot of information about the operating system. In this example we'll see how to fetch and display the memory of the device. We'll also use the thousands crate to commafy the numbers to make them more readable.

Dependencies in the Cargo.toml file

examples/show-used-and-free-memory/Cargo.toml

[package]
name = "show-used-and-free-memory"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
sysinfo = "0.30.7"
thousands = "0.2.0"

The source code

examples/show-used-and-free-memory/src/main.rs

use sysinfo::System;
use thousands::Separable;

fn main() {
    show_memory();
}

fn show_memory() {
    let mut sys = System::new_all();
    sys.refresh_all();

    println!(
        "total memory: {:>15} bytes",
        sys.total_memory().separate_with_commas()
    );
    println!(
        "used memory : {:>15} bytes",
        sys.used_memory().separate_with_commas()
    );
    println!(
        "total swap  : {:>15} bytes",
        sys.total_swap().separate_with_commas()
    );
    println!(
        "used swap   : {:>15} bytes",
        sys.used_swap().separate_with_commas()
    );
}

The output on my computer:

total memory:  29,166,948,352 bytes
used memory :   8,064,937,984 bytes
total swap  :   8,589,930,496 bytes
used swap   :   3,432,517,632 bytes

The {:>15} formatting will pad the field up to 15 characters and right-align the content.

The functions total_memory, used_memory, total_swap, used_swap return u64 64 bit unsigned integers.

The separate_with_commas converts the numbers into more readable strings.

Related Pages

Press ENTER to continue

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo