Skip to main content

Overview

Memory Monitor tracks system memory usage by reading data directly from the /proc/meminfo file, a virtual file provided by the Linux kernel that contains real-time memory statistics.

How /proc/meminfo Works

The /proc/meminfo file is a virtual file that doesn’t actually exist on disk. Instead, the Linux kernel generates its contents dynamically whenever a process reads it. This file provides a comprehensive snapshot of the system’s current memory state.
The /proc filesystem is a pseudo-filesystem that provides an interface to kernel data structures. It’s called “proc” because it was originally designed to provide information about processes.

Memory Metrics Explained

Memory Monitor tracks five key memory metrics:
The total amount of usable RAM in the system (physical RAM minus reserved bits and kernel binary code). This value remains constant unless hardware changes occur.
The amount of physical RAM that is completely unused by the system. This does NOT represent available memory, as it doesn’t include memory used for buffers and cache that can be reclaimed.
Memory used for temporary storage of raw disk blocks. This is relatively small and shouldn’t get very large.
Memory used to cache files read from disk (page cache). The kernel can reclaim this memory when applications need it, making it effectively available.
The actual memory being used by applications and the kernel. This is calculated as:
MemUsed = MemTotal - MemFree - Buffers - Cached
This formula gives you the memory that is actively in use and cannot be easily reclaimed.

Implementation Details

Reading Memory Information

The InformationMemory() function reads and parses /proc/meminfo using Python’s pathlib module:
memory_info.py
def InformationMemory() -> str | None:
    information: str = pathlib.Path("/proc/meminfo").read_text()
    mem_free: int = 0
    mem_total: int = 0
    buffers: int = 0
    cached: int = 0

    if not information:
        return None
The function uses pathlib.Path for a modern, object-oriented approach to file handling. The read_text() method reads the entire file contents as a string.

Parsing Strategy

The parser iterates through each line of /proc/meminfo and extracts only the metrics it needs:
memory_info.py
information: list[str] = information.strip().splitlines()
for info in information:
    if (not info.startswith("MemTotal:") and 
        not info.startswith("MemFree:") and
        not info.startswith("Buffers:") and 
        not info.startswith("Cached:")):
        continue

    if info.startswith("MemTotal:"):
        mem_total: int = int(info.split()[1])
    elif info.startswith("MemFree:"):
        mem_free: int = int(info.split()[1])
    elif info.startswith("Buffers:"):
        buffers: int = int(info.split()[1])
    elif info.startswith("Cached:"):
        cached: int = int(info.split()[1])
This approach:
  • Splits the text into lines using splitlines()
  • Filters for relevant metrics using startswith() checks
  • Extracts values by splitting on whitespace and taking the second element (index 1)
  • Converts to integers for mathematical operations
The values in /proc/meminfo are in kilobytes (kB). Make sure to handle unit conversions appropriately if displaying in MB or GB.

Calculating Memory Usage

The actual memory in use is calculated by subtracting reclaimable memory from the total:
memory_info.py
mem_used: int = mem_total - mem_free - buffers - cached
This calculation gives you the memory that is actively being used by applications and the kernel, excluding memory that can be quickly freed if needed.

Output Format

The function returns a formatted string with all memory metrics:
memory_info.py
return f"Memoria Total: {mem_total} kB\nMemoria Libre: {mem_free} kB\nBuffers: {buffers} kB\nCached: {cached} kB\nMemoria Usada: {mem_used} kB"

Key Design Decisions

Memory Monitor is designed to be lightweight with minimal dependencies. Reading from /proc directly eliminates external dependencies and provides full control over what data is collected.
/proc/meminfo contains dozens of memory metrics. By filtering for only the essential metrics, Memory Monitor minimizes processing time and keeps the output focused on the most relevant information.
/proc/meminfo doesn’t provide a “MemUsed” field directly. The calculation MemTotal - MemFree - Buffers - Cached is the standard way to determine actual memory usage on Linux systems.

Example /proc/meminfo Output

Here’s what a typical /proc/meminfo file looks like:
MemTotal:       16384000 kB
MemFree:         8192000 kB
MemAvailable:   12288000 kB
Buffers:          512000 kB
Cached:          3072000 kB
SwapCached:            0 kB
...
Memory Monitor extracts the highlighted metrics and calculates:
MemUsed = 16384000 - 8192000 - 512000 - 3072000 = 4608000 kB

Next Steps

Process Analysis

Learn how Memory Monitor identifies which processes are consuming the most memory

Build docs developers (and LLMs) love