Explain Codes LogoExplain Codes Logo

How to get current CPU and RAM usage in Python?

python
performance
multiprocessing
memory-usage
Nikita BarsukovbyNikita Barsukov·Sep 12, 2024
TLDR

Launch the psutil library to quickly measure CPU and RAM usage in Python:

import psutil print(f"CPU Usage: {psutil.cpu_percent()}%") print(f"RAM Usage: {psutil.virtual_memory().percent}%")

Install it by running pip install psutil. Fire the code snippet to see the magic.

Rich Insights with psutil

psutil brings an array of insights on system performance, presented in a highly accessible and user-friendly manner.

CPU usage per core

Beyond global CPU usage, psutil can fetch usage data for individual CPU cores. A crucial ability for understanding load distribution:

# Total CPU Utilization print(f"Overall CPU Usage: {psutil.cpu_percent()}%") # CPU Utilization per core for i, percentage in enumerate(psutil.cpu_percent(percpu=True)): print(f"Core {i}: {percentage}%")

Live monitoring with progress bars

For witnessing your system's performance in real-time, loop data fetch. Combine psutil with tqdm to fetch a graphical display of CPU and RAM usage:

from tqdm import tqdm import time # Real-time CPU and RAM usage with tqdm progress bar for _ in tqdm(range(100), desc="Measuring CPU and RAM...like a boss"): print(f"CPU Usage: {psutil.cpu_percent()}%") print(f"RAM Usage: {psutil.virtual_memory().percent}%") time.sleep(1)

Sly usage of multiprocessing

Leverage multiprocessing for CPU-intensive tasks. Offload the monitoring process to spare cores for efficient performance:

import multiprocessing import psutil def ninja_monitor(): # Stealthily monitors the system, in another process print(f"CPU Usage: {psutil.cpu_percent()}%") print(f"RAM Usage: {psutil.virtual_memory().percent}%") if __name__ == '__main__': ninja_process = multiprocessing.Process(target=ninja_monitor) ninja_process.start() ninja_process.join() # Await the ninja's report

Spy on Python process memory

To see how much memory a specific Python process is consuming:

# Memory consumption of the current Python process in GB python_process = psutil.Process() print(f"RAM used by Python: {python_process.memory_info()[0] / 2.**30:.2f} GB")

Handling different environments

psutil and tqdm mix well in various settings, such as a Jupyter notebook. This allows seamless resource monitoring without shifting your usual coding environment. Here's how you mix psutil into a Jupyter notebook:

# Paste this cell at the beginning of your Jupyter notebook for non-stop monitoring from IPython.display import display, HTML import psutil def flashy_status(): while True: cpu_usage = psutil.cpu_percent() ram_usage = psutil.virtual_memory().percent display(HTML(f"<div> CPU: {cpu_usage}% RAM: {ram_usage}% </div>")) time.sleep(0.5) # Initiate the flash-status function in a separate thread threading.Thread(target=flashy_status).start()

Version and platform compatibility

As psutil is a cross-platform library, it's crucial to verify your Python version falls within the psutil supported spectrum. Officially, psutil supports Python versions 2.6 to 3.5.

Issues and remedies

While psutil is an effective toolset, there are potential pitfalls:

Memory usage miscalculation

Some systems can inflate memory usage due to shared memory handling. Cross-check with other system tools if the readings seem off.

Accessing comprehensive information

psutil offers a stash of system performance data in a variety of functions. Dive deep into its official documentation to extract maximum benefits.