cpu_count of os module in Python

The os.cpu_count() method in Python returns the number of processors/cores available in the system. In the Python example provided the program creates a number of threads equal to the number of cores and the main thread waits for the children to complete their execution.

Os Updated 20 Nov 2018 2 min read

Method Name

os. cpu_count

Method Signature

os. cpu_count()

Return Value

An integer representing the number of CPUs present in the system.

Overview

  • The method os.cpu_count() of Python returns the number of processors/number of cores present in the system.
  • Knowing the number of CPUs or cores available in the system enables programs to optimally scale to the number of threads/processes required in dynamic way. The Python example below creates a number of threads equal to the number of cores available and the main thread wait for the child threads to complete through join, though other heuristics will as well help as per the configuration and runtime characteristics.

Example

python
import os

import time

from threading import Thread

# Thread function

def ThreadFunction(threadNum):

    for i in range(0, 5):

        time.sleep(1)

        print("Thread number %d printing the value:%d"%(threadNum, i));

# Get the number of processors/cores available in the system

cpuCount = os.cpu_count()

print("Number of processors/cores available in the system:")

print(os.cpu_count())

theradList = []

# Create number of threads equal to number of cores

for i in range(1,cpuCount+1):

    thread = Thread(target=ThreadFunction, args=(i,))

    theradList.append(thread)

    thread.start()

# Make the main thread join the child threads

print("Waiting for threads to complete")

for i in range(cpuCount):

    theradList[i].join()

print("All the child threads have exited")

print("Main Thread Exiting")

Output

Output
Number of processors/cores available in the system:

4

Waiting for threads to complete

Thread number 1 printing the value:0

Thread number 2 printing the value:0

Thread number 4 printing the value:0

Thread number 3 printing the value:0

Thread number 1 printing the value:1

Thread number 2 printing the value:1

Thread number 3 printing the value:1

Thread number 4 printing the value:1

Thread number 1 printing the value:2

Thread number 2 printing the value:2

Thread number 4 printing the value:2

Thread number 3 printing the value:2

Thread number 1 printing the value:3

Thread number 2 printing the value:3

Thread number 3 printing the value:3

Thread number 4 printing the value:3

Thread number 1 printing the value:4

Thread number 3 printing the value:4

Thread number 4 printing the value:4

Thread number 2 printing the value:4

All the child threads have exited

Main Thread Exiting