我想知道使用Python的本地计算机上的CPU数量。 当使用最佳缩放的仅用户空间程序调用时,结果应该是user/real
如time(1)
所输出。
#1楼
如果您对当前进程可用的处理器数量感兴趣,则必须首先检查cpuset 。 否则(或者如果未使用cpuset), multiprocessing.cpu_count()
是在Python 2.6及更高版本中使用的方法。 以下方法可回溯到旧版本的Python中的两个替代方法:
import os
import re
import subprocess
def available_cpu_count():
""" Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program"""
# cpuset
# cpuset may restrict the number of *available* processors
try:
m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
open('/proc/self/status').read())
if m:
res = bin(int(m.group(1).replace(',', ''), 16)).count('1')
if res > 0:
return res
except IOError:
pass
# Python 2.6+
try:
import multiprocessing
return multiprocessing.cpu_count()
except (ImportError, NotImplementedError):
pass
# https://github.com/giampaolo/psutil
try:
import psutil
return psutil.cpu_count() # psutil.NUM_CPUS on old versions
except (ImportError, AttributeError):
pass
# POSIX
try:
res = int(os.sysconf('SC_NPROCESSORS_ONLN'))
if res > 0:
return res
except (Attribut