Getting the number of CPU cores in a computer is very important for performance optimization and multithreaded programming. Python's os module provides a simple way to get this information. Below we will show how to use the os module to get the number of CPU cores.

Using the os module

Python's os module contains a function os.cpu_count() that can be used to get the number of CPU cores in the system. The following is a sample code:

import os

def get_cpu_cores():
    return os.cpu_count()

cpu_cores = get_cpu_cores()
print(f"CPU核心数量是: {cpu_cores}")

Program running results

CPU核心数量是: 8

os.cpu_count() returns the number of CPU cores on the system, including logical cores. If the system cannot determine the number of cores, it returns None.