Use Python to get the number of CPUs

CPUs can contain single or multiple cores. Single core handles only one process while multi-core handles multiple processes at the same time.

This post will describe different ways to find the total number of CPU cores using a Python program.


Get the number of CPUs in Python using the multiprocessing module

The function in the multiprocessing module cpu_count()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 for interacting with the operating system. os.cpu_count()The command can print the number of CPUs in the system.

The method is the same as the above example, returning the same value on the same machine.

import os
os.cpu_count()

output:

8

This output value is not equal to the number of CPUs available to the current process.

You can use the following command to get the number of available CPUs.

len(os.sched_getaffinity(0))

It only works on certain operating systems, such as Unix.


Get the number of CPUs using the psutil module in Python

psutil is a cross-platform module in Python for obtaining information about running processes and system utilization (CPU, memory, disk, 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

Get the number of CPUs in Python using the joblib module

joblib is a Python package that provides facilities for transparent and fast function disk caching and simple parallel computation.

You can use joblib.cpu_count()the command to see the number of CPUs in the system.

import joblib
joblib.cpu_count()

output:

8

You should now understand how to get the total number of CPUs using different modules in Python. All modules have the same function cpu_count(), which returns the count of CPUs in the system.

You also learned how to find out how many CPUs are available in your computer. We hope you find this article helpful.

Guess you like

Origin blog.csdn.net/fengqianlang/article/details/132136435