User Tools

Site Tools


Sidebar

Go Back

Contact
Recent Changes
Sitemap
snippets:get_physical_cpu_count

Table of Contents

Get physical CPU count

Python

from pathlib import Path


def cpu_count_physical() -> int:
    """Return the number of physical cores in the system."""
    cores = set()
    for path in Path("/sys/devices/system/cpu/").glob("cpu[0-9]*"):
        with open(path / "topology" / "physical_package_id", "rb") as f:
            physical_package_id = int(f.read())
        with open(path / "topology" / "core_id", "rb") as f:
            core_id = int(f.read())
        cores.add((physical_package_id, core_id))
    return len(cores)

Shell

lscpu -p | egrep -v '^#' | sort -u -t, -k 2,4 | wc -l
snippets/get_physical_cpu_count.txt · Last modified: 2021/08/26 14:42 (external edit)