How to get current CPU and RAM usage in Python?
CPU usage or utilization refers to the time taken by a computer to process some information. RAM usage or MAIN MEMORY UTILIZATION on the other hand refers to the amount of time RAM is used by a certain system at a particular time. Both of these can be retrieved using Python.
Get current CPU usage in Python
Get current CPU usage using psutil
The function psutil.cpu_percent() provides the current system-wide CPU utilization in the form of a percentage. It takes a parameter which is the time interval (seconds). Since CPU utilization is calculated over a period of time it is recommended to provide a time interval.
The CPU usage is: 2.4
Get current CPU usage using the OS module
The psutil.getloadavg() provides the load information of the CPU in the form of a tuple. The psutil.getloadavg() runs in the background and the results get updated every 5 seconds. The os.cpu_count() returns the number of CPUs in the system.
The CPU usage is: 13.4
Get current RAM usage in Python
Get current RAM usage using psutil
The function psutil.virutal_memory() returns a named tuple about system memory usage. The third field in the tuple represents the percentage use of the memory(RAM). It is calculated by (total – available)/total * 100 . Sometimes we need the actual value of the system memory used by the running process, to print the actual value, the fourth field in the tuple is used. Since the value returned is in bytes, it should be divided by 10^9 to convert into GB.
The total fields in the output of the function are:
- total: total memory excluding swap
- available: available memory for processes
- percent: memory usage in percent
- used: the memory used
- free: memory not used at and is readily available
RAM memory % used: 76.9 RAM Used (GB): 23.32
Get current RAM usage using the OS module
The os module is also useful for calculating the ram usage in the CPU. The os.popen() method with flags as input can provide the total, available and used memory. This method opens a pipe to or from the command. The return value can be read or written depending on whether a mode is ‘r’ or ‘w’.
RAM memory % used: 17.55
Note: The os module method works with the Linux system only due to the free flag and system command specified for Linux system.