0
0
PythonHow-ToBeginner · 3 min read

How to Get CPU Count in Python: Simple Guide

You can get the CPU count in Python using multiprocessing.cpu_count(). This function returns the number of logical CPUs available on your machine.
📐

Syntax

The syntax to get the CPU count is simple. You import the multiprocessing module and call the cpu_count() function.

  • multiprocessing: A built-in Python module for process-based parallelism.
  • cpu_count(): Returns the number of logical CPUs.
python
import multiprocessing

cpu_number = multiprocessing.cpu_count()
💻

Example

This example shows how to print the number of CPUs your Python program can use. It helps you decide how many parallel tasks to run.

python
import multiprocessing

print("Number of CPUs available:", multiprocessing.cpu_count())
Output
Number of CPUs available: 8
⚠️

Common Pitfalls

Sometimes people forget to import multiprocessing before calling cpu_count(), which causes an error. Also, cpu_count() returns logical CPUs, not physical cores, so the number might be higher than expected if your CPU supports hyper-threading.

On some rare systems, cpu_count() may return None or raise an exception if the count cannot be determined.

python
import multiprocessing

# Wrong: calling cpu_count without import
# print(cpu_count())  # NameError

# Right way:
print(multiprocessing.cpu_count())
Output
8
📊

Quick Reference

Remember these tips when using multiprocessing.cpu_count():

  • Always import multiprocessing first.
  • Returns logical CPUs, which may differ from physical cores.
  • Use this count to optimize parallel processing tasks.

Key Takeaways

Use multiprocessing.cpu_count() to get the number of logical CPUs.
Always import the multiprocessing module before calling cpu_count().
The returned count may include hyper-threaded cores, not just physical ones.
Use the CPU count to decide how many parallel tasks to run efficiently.