Number of CPU Cores
- Method 1:
If the Python version is later than 2.6, obtain the number of CPUs by using the following module.
The return value of cpu_count is the number of CPUs.
import multiprocessing multiprocessing.cpu_count()
If the Python version is earlier than 2.6, use the following module to obtain the number of CPUs:
import psutil psutil.cpu_count()
- Method 2:
Python can read the system file /proc/cpuinfo and filter the processor field to collect statistics on the number of cores.
Example:
def get_cpu_info(): processor_cnt = 0 cpu_model = "" f_cpu_info = open("/proc/cpuinfo") try: for line in f_cpu_info: if (line.find("processor") == 0): processor_cnt += 1 print("cpu counts: %s, cpu model: %s" % (processor_cnt)) finally: f_cpu_info.close()
Parent topic: Python