Keywords: Python | psutil | CPU usage | RAM usage | system monitoring
Abstract: This technical article demonstrates how to retrieve real-time CPU, RAM, and disk usage in Python with the psutil library. It covers installation, usage examples, and advantages over platform-specific methods, ensuring compatibility across operating systems for performance optimization and debugging.
Introduction
Monitoring system resources such as CPU and memory usage is crucial for optimizing application performance and identifying bottlenecks. In Python, the psutil library provides a portable and efficient way to access this information across various platforms including Linux, Windows, and macOS. It consolidates functionalities from tools like ps and top, offering a unified interface for system utilization data.
Installing psutil
To begin, install psutil using pip: pip install psutil. This library supports Python versions from 2.6 to 3.5 and is actively maintained, making it suitable for both 32-bit and 64-bit architectures.
Monitoring CPU Usage
The psutil.cpu_percent() function returns the CPU utilization as a percentage. By specifying an interval, it averages the usage over that period. For example:
import psutil
cpu_usage = psutil.cpu_percent(interval=1)
print(f"Current CPU usage: {cpu_usage}%")This code measures CPU usage over one second and prints the result, providing a reliable snapshot of system load.
Monitoring RAM Usage
For memory, use psutil.virtual_memory(), which returns a named tuple with fields like total, available, used, and percent. Example:
ram = psutil.virtual_memory()
print(f"RAM usage: {ram.percent}%")
print(f"Used RAM: {ram.used / 1e9:.2f} GB")This outputs the percentage of used RAM and the amount in gigabytes. Additional calculations, such as available memory percentage, can be derived from the tuple fields.
Monitoring Disk Usage
Disk usage can be monitored with psutil.disk_usage(path). For the root directory:
disk = psutil.disk_usage('/')
print(f"Disk usage: {disk.percent}%")This provides the percentage of disk space used, aiding in storage management across different file systems.
Other Monitoring Approaches
While platform-specific methods like using os.popen('free -m') on Linux exist, they lack cross-platform support. Psutil unifies these approaches, offering a consistent API. Additionally, psutil.getloadavg() can estimate CPU load but is less real-time than cpu_percent.
Conclusion
Psutil offers a robust solution for system monitoring in Python, enabling developers to easily track CPU, RAM, and disk usage across different operating systems. Its ease of use and active development make it ideal for performance optimization and debugging, recommended for projects requiring cross-platform compatibility.