Skip to main content

Running Memory Monitor

Memory Monitor is simple to run. Once you have it installed, you can execute it from the command line.
1

Navigate to the Directory

Open your terminal and navigate to the directory containing Memory Monitor:
cd /path/to/memory-monitor
2

Execute the Main Script

Run Memory Monitor using Python 3:
python3 main.py
The tool will immediately start collecting and displaying memory information.
3

Review the Output

Memory Monitor will display two sections:
  1. System memory statistics
  2. The process with the highest memory consumption
See below for details on interpreting this output.

Understanding the Output

When you run Memory Monitor, you’ll see output similar to this:
==========MEMORY MONITOR==========
Memoria Total: 16384000 kB
Memoria Libre: 4096000 kB
Buffers: 512000 kB
Cached: 6144000 kB
Memoria Usada: 5632000 kB
==============================
El proceso con mayor VmRSS es 
 Name: firefox
 PID: 1234
 VmRSS: 2048000 kB

System Memory Section

The first section displays overall system memory statistics:
  • Memoria Total - Total physical RAM installed in your system (in kilobytes)
  • Memoria Libre - Memory currently not being used (in kilobytes)
  • Buffers - Memory used for disk I/O buffers (in kilobytes)
  • Cached - Memory used for file system cache (in kilobytes)
  • Memoria Usada - Actively used memory, calculated as: MemTotal - MemFree - Buffers - Cached
Buffers and cached memory are available for applications when needed, so they’re excluded from the “used” memory calculation. This provides a more accurate picture of memory pressure.

Process Analysis Section

The second section identifies the single process consuming the most resident memory:
  • Name - The name of the process
  • PID - The process ID
  • VmRSS - Virtual Memory Resident Set Size - the amount of physical RAM actually used by this process (in kilobytes)
VmRSS represents the actual physical memory occupied by a process, excluding swapped-out pages. This is the most accurate measure of a process’s real memory consumption.

How It Works Under the Hood

Memory Monitor uses two core functions to gather this information:

Memory Information Collection

The InformationMemory() function in memory_info.py reads directly from /proc/meminfo:
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
    
    information: list[str] = information.strip().splitlines()
    for info in information:
        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])
    
    mem_used: int = mem_total - mem_free - buffers - cached
    
    return f"Memoria Total: {mem_total} kB\n..."
This function parses /proc/meminfo to extract the key memory metrics and calculates used memory.

Process Analysis

The ListDirectory() function in process_analyzer.py scans all running processes:
def ListDirectory() -> list[str, str] | None:
    list_directory: list[str] = os.listdir("/proc")
    pids = [pid for pid in list_directory if pid.isdigit()]
    max_vmrrs: int = 0
    max_pid: str = ""
    max_process_name: str = ""
    
    for pid in pids:
        status_path = os.path.join("/proc", pid, "status")
        try:
            with open(status_path, "r") as f:
                vmrrs = 0
                for line in f:
                    if line.startswith("Name:"):
                        max_process_name = line.strip().split()[1]
                    if line.startswith("VmRSS:"):
                        vmrrs = int(line.strip().split()[1])
                        if vmrrs > max_vmrrs:
                            max_vmrrs = vmrrs
                            max_pid = pid
        except (FileNotFoundError, PermissionError):
            continue
    
    return [f"El proceso con mayor VmRSS es..."]
This function iterates through each process directory in /proc, reads the status file, and tracks which process has the highest VmRSS value.

Common Use Cases

Diagnosing High Memory Usage

When your system feels slow, run Memory Monitor to see if memory pressure is the cause and which process is consuming the most RAM.

Monitoring After Deployment

After deploying a new application, run Memory Monitor periodically to ensure it’s not leaking memory or consuming more than expected.

System Health Checks

Include Memory Monitor in your regular system health check routine to catch memory issues before they become critical.

Performance Troubleshooting

When users report slowness, quickly identify if a specific process has excessive memory consumption.

Running with Elevated Privileges

Some processes may require root access to read their status information. To get complete information:
sudo python3 main.py
This ensures Memory Monitor can access all process information without encountering permission errors.

Tips for Effective Monitoring

  • Run periodically - Memory consumption changes over time. Run Memory Monitor at regular intervals to track trends
  • Compare results - Note the highest memory consumer and track if it changes or grows over time
  • Watch for leaks - If the same process consistently shows increasing VmRSS values, it may have a memory leak
  • Correlate with performance - High “Memoria Usada” with low “Memoria Libre” indicates memory pressure

Next Steps

Now that you understand how to run Memory Monitor and interpret its output, you can:
  • Incorporate it into your monitoring scripts
  • Schedule it to run periodically via cron
  • Extend the code to log results to a file
  • Modify it to alert when memory usage exceeds thresholds
The source code is straightforward Python and easy to customize for your specific needs!

Build docs developers (and LLMs) love