How to Get Current CPU and RAM Usage in Python
Monitoring CPU and RAM usage in Python is essential for performance profiling, system monitoring dashboards, resource-aware applications, and debugging memory leaks. Whether you need system-wide metrics or per-process statistics, Python provides several ways to retrieve real-time resource usage.
In this guide, we'll cover the most practical methods with clear examples and outputs.
Quick Answer: Use psutil
The psutil (process and system utilities) library is the most reliable and cross-platform way to get CPU and RAM usage:
import psutil
# CPU usage (measured over a 1-second interval)
cpu = psutil.cpu_percent(interval=1)
print(f"CPU Usage: {cpu}%")
# RAM usage
ram = psutil.virtual_memory()
print(f"RAM Usage: {ram.percent}%")
print(f"RAM Used: {ram.used / (1024 ** 3):.2f} GB")
print(f"RAM Total: {ram.total / (1024 ** 3):.2f} GB")
Output:
CPU Usage: 18.1%
RAM Usage: 62.4%
RAM Used: 9.97 GB
RAM Total: 15.98 GB
If psutil isn't installed:
pip install psutil
Getting CPU Usage
System-Wide CPU Usage with psutil.cpu_percent()
cpu_percent() returns the CPU utilization as a percentage. The interval parameter specifies how long to measure over; a longer interval gives a more accurate reading:
import psutil
# Overall CPU usage (1-second measurement)
print(f"Overall CPU: {psutil.cpu_percent(interval=1)}%")
# Per-core CPU usage
per_core = psutil.cpu_percent(interval=1, percpu=True)
for i, usage in enumerate(per_core):
print(f" Core {i}: {usage}%")
Output:
Overall CPU: 23.5%
Core 0: 35.2%
Core 1: 18.8%
Core 2: 27.1%
Core 3: 12.9%
Setting interval=None (or interval=0) returns the CPU usage since the last call, which is useful for continuous monitoring:
import psutil
import time
psutil.cpu_percent() # First call initializes: discard this result
time.sleep(1)
print(f"CPU: {psutil.cpu_percent()}%") # Accurate reading since last call
CPU Core Count
import psutil
print(f"Physical cores: {psutil.cpu_count(logical=False)}")
print(f"Logical cores: {psutil.cpu_count(logical=True)}")
Output:
Physical cores: 4
Logical cores: 8
System Load Average (Linux/macOS)
The load average represents the average number of processes waiting for CPU time over 1, 5, and 15 minutes:
import os
import psutil
load1, load5, load15 = psutil.getloadavg()
cores = os.cpu_count()
print(f"Load Average (1 min): {load1:.2f}")
print(f"Load Average (5 min): {load5:.2f}")
print(f"Load Average (15 min): {load15:.2f}")
print(f"CPU Usage Estimate: {(load1 / cores) * 100:.1f}%")
Output:
Load Average (1 min): 1.45
Load Average (5 min): 1.72
Load Average (15 min): 1.68
CPU Usage Estimate: 18.1%
getloadavg() returns (0.0, 0.0, 0.0) on Windows since the concept of load average doesn't exist there. Use cpu_percent() on Windows instead.
Getting RAM Usage
System-Wide RAM with psutil.virtual_memory()
This returns detailed information about the system's physical memory:
import psutil
ram = psutil.virtual_memory()
print(f"Total: {ram.total / (1024 ** 3):.2f} GB")
print(f"Available: {ram.available / (1024 ** 3):.2f} GB")
print(f"Used: {ram.used / (1024 ** 3):.2f} GB")
print(f"Percent: {ram.percent}%")
Output:
Total: 15.98 GB
Available: 6.01 GB
Used: 9.97 GB
Percent: 62.4%
The fields returned by virtual_memory():
| Field | Description |
|---|---|
total | Total physical memory |
available | Memory that can be given to processes without swapping |
used | Memory currently in use |
free | Memory not being used at all |
percent | Percentage of memory used ((total - available) / total * 100) |
Swap Memory
import psutil
swap = psutil.swap_memory()
print(f"Swap Total: {swap.total / (1024 ** 3):.2f} GB")
print(f"Swap Used: {swap.used / (1024 ** 3):.2f} GB")
print(f"Swap Usage: {swap.percent}%")
Output:
Swap Total: 8.00 GB
Swap Used: 0.45 GB
Swap Usage: 5.6%
Monitoring the Current Python Process
Memory Usage of Your Script
To monitor how much memory your own Python program is using:
import os
import psutil
process = psutil.Process(os.getpid())
mem_info = process.memory_info()
print(f"RSS (Resident Set Size): {mem_info.rss / (1024 ** 2):.2f} MB")
print(f"VMS (Virtual Memory): {mem_info.vms / (1024 ** 2):.2f} MB")
Output:
RSS (Resident Set Size): 25.86 MB
VMS (Virtual Memory): 412.50 MB
| Metric | Description |
|---|---|
| RSS | Physical memory actually used by the process |
| VMS | Total virtual memory allocated (includes shared libraries) |
CPU Usage of Your Script
import os
import psutil
process = psutil.Process(os.getpid())
# CPU usage of this process (as percentage of one core)
print(f"Process CPU: {process.cpu_percent(interval=1)}%")
Using resource Module (Linux/macOS Only)
Python's built-in resource module provides peak memory usage without any external dependencies:
import resource
# Peak memory usage in kilobytes (Linux) or bytes (macOS)
usage = resource.getrusage(resource.RUSAGE_SELF)
print(f"Peak memory: {usage.ru_maxrss / 1024:.2f} MB") # Linux
# On macOS: usage.ru_maxrss is already in bytes, divide by 1024**2
Output (Linux):
Peak memory: 25.42 MB
The resource module is not available on Windows. Use psutil for cross-platform compatibility.
Continuous Monitoring Script
Here's a practical script that monitors CPU and RAM usage in real time:
import psutil
import time
from datetime import datetime
def monitor(interval=2, duration=10):
"""Monitor CPU and RAM usage at regular intervals."""
print(f"{'Time':<12} {'CPU %':>6} {'RAM %':>6} {'RAM Used':>10}")
print("-" * 40)
end_time = time.time() + duration
while time.time() < end_time:
cpu = psutil.cpu_percent(interval=0)
ram = psutil.virtual_memory()
now = datetime.now().strftime("%H:%M:%S")
print(f"{now:<12} {cpu:>5.1f}% {ram.percent:>5.1f}% "
f"{ram.used / (1024 ** 3):>8.2f} GB")
time.sleep(interval)
monitor(interval=2, duration=10)
Output:
Time CPU % RAM % RAM Used
----------------------------------------
14:30:01 12.3% 62.4% 9.97 GB
14:30:03 18.7% 62.5% 9.99 GB
14:30:05 8.2% 62.3% 9.96 GB
14:30:07 15.1% 62.4% 9.97 GB
14:30:09 11.5% 62.4% 9.97 GB
Getting a Complete System Summary
import psutil
import platform
def system_summary():
"""Print a complete system resource summary."""
print("=" * 50)
print("SYSTEM RESOURCE SUMMARY")
print("=" * 50)
# System info
print(f"\nSystem: {platform.system()} {platform.release()}")
print(f"Processor: {platform.processor()}")
# CPU
print(f"\nCPU Cores: {psutil.cpu_count(logical=False)} physical, "
f"{psutil.cpu_count(logical=True)} logical")
print(f"CPU Usage: {psutil.cpu_percent(interval=1)}%")
# RAM
ram = psutil.virtual_memory()
print(f"\nRAM Total: {ram.total / (1024 ** 3):.2f} GB")
print(f"RAM Used: {ram.used / (1024 ** 3):.2f} GB ({ram.percent}%)")
print(f"RAM Available: {ram.available / (1024 ** 3):.2f} GB")
# Disk
disk = psutil.disk_usage('/')
print(f"\nDisk Total: {disk.total / (1024 ** 3):.2f} GB")
print(f"Disk Used: {disk.used / (1024 ** 3):.2f} GB ({disk.percent}%)")
print(f"Disk Free: {disk.free / (1024 ** 3):.2f} GB")
system_summary()
Output:
==================================================
SYSTEM RESOURCE SUMMARY
==================================================
System: Linux 5.15.0-78-generic
Processor: x86_64
CPU Cores: 4 physical, 8 logical
CPU Usage: 15.3%
RAM Total: 15.98 GB
RAM Used: 9.97 GB (62.4%)
RAM Available: 6.01 GB
Disk Total: 465.63 GB
Disk Used: 198.42 GB (42.6%)
Disk Free: 243.49 GB
Method Comparison
| Method | CPU | RAM | Cross-Platform | External Dependency |
|---|---|---|---|---|
psutil.cpu_percent() | ✅ | ❌ | ✅ | psutil |
psutil.virtual_memory() | ❌ | ✅ | ✅ | psutil |
psutil.Process().memory_info() | ❌ | ✅ (process only) | ✅ | psutil |
psutil.getloadavg() | ✅ (estimate) | ❌ | Linux/macOS only | psutil |
resource.getrusage() | ❌ | ✅ (peak only) | Linux/macOS only | None (built-in) |
os.popen('free') | ❌ | ✅ | Linux only | None (built-in) |
Conclusion
The psutil library is the most reliable and cross-platform way to get CPU and RAM usage in Python.
- Use
psutil.cpu_percent(interval=1)for CPU utilization andpsutil.virtual_memory()for detailed RAM statistics. - For monitoring your own Python process, use
psutil.Process(os.getpid()).memory_info().
These methods work consistently across Windows, macOS, and Linux, making psutil the go-to choice for system resource monitoring in Python applications.