How to get current CPU and RAM usage in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To get the current CPU and RAM usage in Python, you can use the psutil library. Here’s an example of how to use it:

import psutil

# Get CPU usage as a percentage
cpu_percent = psutil.cpu_percent()

# Get memory usage in bytes
memory_usage = psutil.virtual_memory().used

print(f"Current CPU usage: {cpu_percent}%")
print(f"Current memory usage: {memory_usage} bytes")

This will print out the current CPU usage as a percentage and the current memory usage in bytes. Note that psutil.cpu_percent() returns the CPU usage as a percentage since the last time it was called, so you may want to call it multiple times and use the average value.

Additionally, psutil.virtual_memory() returns a named tuple with information about virtual memory usage on the system, including used, free, available, and percent.

Keep in mind that getting CPU and RAM usage may vary across different operating systems and hardware configurations.

To continuously monitor the current CPU and RAM usage in Python using while loop, you can use the psutil library. Here’s an example:

import psutil
import time
while True:
    # Get CPU usage as a percentage
    cpu_percent = psutil.cpu_percent()

    # Get memory usage in bytes, then convert to MB
    memory_usage = psutil.virtual_memory().used / (1024 * 1024)

    print(f"Current CPU usage: {cpu_percent}%")
    print(f"Current memory usage: {memory_usage:.2f} MB\n")

    # Wait for some time before checking again
    time.sleep(1)

In this example, the while loop will continuously print out the current CPU usage as a percentage and the current memory usage in MB, and then wait for 1 second before checking again. You can change the sleep time to adjust how frequently the check is performed.

It’s important to note that continuously monitoring the CPU and RAM usage using a while loop can potentially cause your application to slow down or become unresponsive. So it’s recommended to use this method with caution and only in situations where it’s necessary.

Tags:

related content