How to Get the Number of CPUs Using Python

Rohan Timalsina Feb 02, 2024
  1. Use the multiprocessing Module to Get the Number of CPUs in Python
  2. Use the os Module to Get the Number of CPUs in Python
  3. Use the psutil Module to Get the Number of CPUs in Python
  4. Use the joblib Module to Get the Number of CPUs in Python
How to Get the Number of CPUs Using Python

A CPU can contain a single core or multiple cores. Single cores work on only one process, whereas multiple cores work on multiple processes simultaneously.

This tutorial will introduce different methods to find the total number of CPU cores using a Python program.

Use the multiprocessing Module to Get the Number of CPUs in Python

The cpu_count() function in the multiprocessing module gets the total number of CPUs in the system.

import multiprocessing

multiprocessing.cpu_count()

Output:

8

Use the os Module to Get the Number of CPUs in Python

The os module provides functions to interact with the operating system. The os.cpu_count() command can print the number of CPUs in the system.

This method is the same as the above example and returns the same value in the same machine.

import os

os.cpu_count()

Output:

8

This output value does not equal the number of CPUs the current process can use.

You can obtain the number of usable CPUs using the command below.

len(os.sched_getaffinity(0))

It only works in some operating systems, such as Unix.

Use the psutil Module to Get the Number of CPUs in Python

psutil is a cross-platform module in Python to get information on running processes and system utilization (CPU, memory, disks, network, sensors).

You can install the psutil library using the following command.

pip install psutil

To determine the number of CPUs using psutil, execute these commands.

import psutil

psutil.cpu_count()

Output:

8

Use the joblib Module to Get the Number of CPUs in Python

joblib is a Python package that provides tools for transparent and fast disk-caching of functions and easy parallel computing.

You can view the number of CPUs in the system using the joblib.cpu_count() command.

import joblib

joblib.cpu_count()

Output:

8

Now you should have understood how to obtain the total number of CPUs using different modules in Python. All modules have the same function, cpu_count(), that returns the CPUs count in the system.

You have also learned how to find out the number of usable CPUs in the computer. We hope you find this tutorial helpful.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - Python CPU