What is psutil.cpu_count method in Python?

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). 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_count method

The cpu_count method is used to return the current number of logical CPUs in the system.

Syntax

cpu_count(logical=True)

Parameter and return value

The method takes one parameter:

  • logical: The logical parameter is a boolean value that represents whether to return the logical CPUs or the number of the physical CPUs. By default, the value of the parameter is set to True. Setting it to False returns the number of physical CPUS/cores in the system.

Note: A logical CPU/core is a hyperthreaded CPU/core. The total number of logical cores in a system is the number of physical cores multiplied by the number of threads each core can execute.

Example

import psutil
print("The number of physical cores in the system is %s" % (psutil.cpu_count(logical=False),))
print("The number of logical cores in the system is %s" % (psutil.cpu_count(logical=True),))

Code explanation

  • Line 1: We import the psutil module.
  • Line 3: We retrieve the number of physical cores in the system by calling the cpu_count() method with the logical parameter as False.
  • Line 5: We retrieve the number of logical cores in the system by calling the cpu_count() method with the logical parameter as True.

Free Resources