Python
CPU count
Programming
System Information
Coding Tutorial

How to find out the number of CPUs using python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Python gives you a few different ways to ask how many CPUs are available, and the right one depends on what you mean by "CPU." Sometimes you want the total logical processor count, sometimes the physical core count, and sometimes you only want the CPUs that the current process is allowed to use.

Use os.cpu_count() for the Basic Answer

The standard-library answer is os.cpu_count(). It returns the number of logical CPUs visible to the operating system, which usually includes hyper-threaded cores.

python
1import os
2
3count = os.cpu_count()
4print(count)

This is the simplest and most portable option. On many machines it will return values such as 8, 12, or 16. If Python cannot determine the count, it may return None, so production code should handle that case.

python
1import os
2
3count = os.cpu_count() or 1
4print(f"usable default count: {count}")

For many scripts, especially quick parallel-processing experiments, that is enough.

multiprocessing.cpu_count() Says the Same Thing

The multiprocessing module also exposes cpu_count(). In practice it serves the same purpose and usually returns the same logical CPU count.

python
import multiprocessing

print(multiprocessing.cpu_count())

This is convenient when you are already writing multiprocessing code and want to size a worker pool near the hardware limit.

python
1from multiprocessing import Pool, cpu_count
2
3def square(x):
4    return x * x
5
6with Pool(processes=cpu_count()) as pool:
7    print(pool.map(square, [1, 2, 3, 4]))

Even here, though, the full logical CPU count is not always the best worker count. Real workloads may perform better with fewer processes.

Distinguish Logical and Physical Cores

The standard library does not directly tell you the number of physical cores. If you need that distinction, psutil is a common choice.

python
1import psutil
2
3print("logical:", psutil.cpu_count(logical=True))
4print("physical:", psutil.cpu_count(logical=False))

This matters when you are tuning CPU-bound workloads. Logical CPUs include simultaneous multithreading, which can help some tasks but does not behave like having twice as many real cores.

If psutil is not installed:

bash
pip install psutil

Use physical core counts when you want a more conservative estimate of true parallel compute capacity.

Consider CPU Affinity in Containers and Restricted Environments

On Linux, the machine may have many CPUs while the current process is allowed to run on only a subset of them. That can happen in containers, job schedulers, or systems that use CPU affinity.

In those cases, os.cpu_count() may overstate the CPUs you can actually use. A better Linux-specific answer is the size of the affinity set:

python
1import os
2
3if hasattr(os, "sched_getaffinity"):
4    print(len(os.sched_getaffinity(0)))
5else:
6    print(os.cpu_count())

That is often the most practical number for process pools inside constrained runtime environments.

Pick the Count Based on the Workload

The CPU count is not automatically the correct number of threads or processes.

  • CPU-bound multiprocessing jobs often start near the number of physical or allowed CPUs
  • I/O-bound tasks may benefit from more threads than CPUs
  • heavily memory-bound jobs may need fewer workers than the hardware allows

A small benchmark is usually better than blindly using the raw CPU count.

For example:

python
1import os
2from concurrent.futures import ThreadPoolExecutor
3
4workers = min(32, (os.cpu_count() or 1) + 4)
5print(f"thread count: {workers}")
6
7with ThreadPoolExecutor(max_workers=workers) as executor:
8    results = list(executor.map(lambda x: x + 1, range(5)))
9    print(results)

This is a reminder that CPU detection is only the starting point for performance tuning.

Common Pitfalls

The biggest mistake is assuming os.cpu_count() means physical cores. It usually reports logical CPUs. Another common issue is using the total machine count inside a container even though the process is limited by affinity or cgroup settings. Developers also tend to treat the CPU count as the correct worker count automatically, which is not true for many I/O-heavy or memory-heavy workloads. Finally, code that assumes the count is never None can fail on less common platforms.

Summary

  • Use os.cpu_count() for a quick, portable logical CPU count.
  • 'multiprocessing.cpu_count() provides the same kind of answer and fits multiprocessing code naturally.'
  • Use psutil.cpu_count(logical=False) if you need physical core estimates.
  • On Linux, os.sched_getaffinity(0) can be more accurate in restricted environments.
  • Treat CPU count as an input to tuning, not as the final answer for worker configuration.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.