How to get current CPU and RAM usage in Python?
Last Updated : 13 Jun, 2025
Getting the current CPU and RAM usage in Python involves retrieving real-time information about how much processing power and memory your system is using at any given moment. For example, knowing that your CPU is at 18% usage and your RAM is 40% utilized can help monitor system performance or optimize your applications. Let’s explore different methods to do this efficiently.
Using psutil.virtual_memory()
This method uses the psutil library to get real-time CPU and RAM usage. It measures CPU utilization over a short interval and reports detailed RAM statistics like the percentage used and the actual memory consumed. It works well across different operating systems and is both accurate and easy to use.
Python import psutil print("CPU usage (%):", psutil.cpu_percent(interval=1)) ram = psutil.virtual_memory() print("RAM usage (%):", ram.percent) print("RAM used (GB):", round(ram.used / 1e9, 2))
Output
CPU usage (%): 18.1
RAM usage (%): 87.4
RAM used (GB): 7.21
Explanation: psutil measures CPU usage over one second and retrieves memory details, printing RAM usage percentage and used RAM in gigabytes rounded to two decimals.
Using psutil.getloadavg()
By dividing the load by the number of CPU cores, you get a percentage estimate of CPU usage. It’s useful for understanding overall system workload trends rather than moment-to-moment CPU activity.
Python import os import psutil load1, load5, load15 = psutil.getloadavg() cpu_usage = (load1 / os.cpu_count()) * 100 print(round(cpu_usage, 2), "%")
Output
0.0 %
Explanation: psutil and os get the 1, 5 and 15-minute load averages, then calculate CPU usage by dividing the 1-minute load by CPU cores and converting it to a percentage.
Using psutil.Process().memory_info()
This approach focuses on monitoring how much memory the current Python process is using. It reports the memory usage in megabytes and is helpful when you want to profile or optimize your own program’s memory consumption.
Python import os import psutil process = psutil.Process(os.getpid()) ram_used = process.memory_info().rss / (1024 * 1024) # in MB print(round(ram_used, 2))
Output
25.86
Explanation: psutil and os measure the current Python process’s memory by getting its PID, retrieving the resident set size (rss) in bytes, converting it to megabytes, and rounding to two decimals.
Using os.popen()
This method runs the Linux command free through Python’s os.popen() and parses its output to find RAM usage. It’s a quick way to get memory information on Linux systems but isn’t portable to other operating systems.
Python import os total, used, free = map(int, os.popen('free -t -m').readlines()[-1].split()[1:]) print(round((used / total) * 100, 2))
Output
52.34
Explanation: This code uses the os module to run the Linux free command, extracts total and used memory in MB, calculates used memory percentage and prints it rounded to two decimals.