What is psutil.cpu_percent in Python?

What is the psutil module?

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

The cpu_percent method is used to return the current system-wide CPU utilization as a percentage.

Syntax

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.

Example

import psutil
print("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), ))

Explanation

  • Line 1: We import the psutil module.
  • Line 3: We retrieve the CPU utilization using the cpu_percent(), with the interval as 2 seconds.
  • Line 5: We retrieve the CPU utilization using the cpu_percent() with interval as 2 seconds.
  • Line 7: We get the number of CPUs using the psutil.cpu_count() method.
  • Line 9: We retrieve the utilization of every CPU by invoking the 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.