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). It is mostly used for system monitoring, profiling, restricting process resources, and process management.
The module can be installed via pip
as follows:
pip install psutil
The cpu_percent
method is used to return the current system-wide CPU utilization as a percentage.
cpu_percent(interval=None, percpu=False)
The method takes two parameters.
interval
: This parameter represents the time interval over which the method calculates the CPU usage. Giving interval > 0
results in a blocking call where the CPU usage is calculated.
percpu
: This is a boolean parameter. When set to true
, the method returns a list indicating the utilization of each CPU in the system.
import psutilprint("psutil.cpu_percent(interval=2) = %s" % (psutil.cpu_percent(interval=2),))print("psutil.cpu_percent(interval=2) = %s" % (psutil.cpu_percent(interval=2),))print("The number of CPUs is : %s" % (psutil.cpu_count(), ))print("The CPU utilization of all the CPUs is: %s" % (psutil.cpu_percent(interval=2, percpu=True), ))
psutil
module.cpu_percent()
, with the interval as 2 seconds.cpu_percent()
with interval as 2 seconds.cpu_percent()
method with the percpu
parameter as true
. The method returns a list. The first value of the list corresponds to the first CPU utilization, the second value corresponds to the second CPU utilization, and so on.