What is the psutil.getloadavg() method?
What is the psutil module?
The psutil (python system and process utilities) is a Python package that retrieves information on ongoing processes and system usage (CPU, memory, storage, network, and sensors). We mainly use it for system monitoring, profiling, restricting process resources, and process management.
The module can be installed via pip as follows:
pip install psutil
The getloadavg method
System load refers to the processes in a running state or are either utilizing or waiting to use the CPU (for example, waiting for disc I/O).
The getloadavg method returns the average system load. The method returns a tuple with three values which indicate the average system load over the last 1, 5, and 15 minutes.
The number given by this method is just a number, and to better understand it, we convert the number to a percentage. Every number in the tuple returned by the method is divided by the number of logical CPUs, and then the result is multiplied by 100 to get the corresponding percentage.
The code for the above logic is as follows:
num_log_cpus = psutil.cpu_count()
percent_tuple = []
for load in psutil.getloadavg():
percent = (load / num_log_cpus) * 100
percent_tuple.append(percent)
Method signature
psutil.getloadavg()
The method takes no parameters.
Code
import psutildef convert_to_percent(load_tuple):num_log_cpus = psutil.cpu_count()percent_lst = []for load in load_tuple:percent = (load / num_log_cpus) * 100percent_lst.append(percent)return tuple(percent_lst)load_tuple = psutil.getloadavg()print("psutil.psutil.getloadavg() = ", load_tuple)print("Converting to percentage = ", convert_to_percent(load_tuple))
Explanation
- Line 1: We import the
psutilmodule. - Lines 3–12: We define a function called
convert_to_percentthat takes in values returned bygetloadavg()method and converts them into percentage values. - Line 15: We invoke the
getloadavg()method, and the values are stored in the variableload_tuple. - Line 17: We convert
load_tupleto a percentage by invokingconvert_to_percent()method, and the result is printed.