我想用Python知道本地机器上cpu的数量。当使用一个优化伸缩的仅用户空间的程序调用时,结果应该是user/real作为时间(1)的输出。
当前回答
如果您正在寻找打印系统中的核数。
试试这个:
import os
no_of_cores = os.cpu_count()
print(no_of_cores)
这应该会有所帮助。
其他回答
另一种选择是使用psutil库,它在这些情况下总是很有用:
>>> import psutil
>>> psutil.cpu_count()
2
这应该可以在psutil支持的任何平台上工作(Unix和Windows)。
注意在某些情况下多处理。cpu_count可能引发NotImplementedError,而psutil将能够获得cpu的数量。这只是因为psutil首先尝试使用多处理所使用的相同技术,如果这些技术失败,它还会使用其他技术。
这可能适用于我们这些使用不同操作系统的人,但想要获得所有世界的最好:
import os
workers = os.cpu_count()
if 'sched_getaffinity' in dir(os):
workers = len(os.sched_getaffinity(0))
你也可以使用“joblib”来达到这个目的。
import joblib
print joblib.cpu_count()
此方法将为您提供系统中的cpu数量。但是Joblib需要安装。更多关于joblib的信息可以在这里找到https://pythonhosted.org/joblib/parallel.html
或者,您可以使用python的numexpr包。它有很多简单的功能,有助于获取关于系统cpu的信息。
import numexpr as ne
print ne.detect_number_of_cores()
这将提供超线程CPU计数
multiprocessing.cpu_count () os.cpu_count ()
这些参数提供了虚拟机CPU计数
psutil.cpu_count () numexpr.detect_number_of_cores ()
只有在虚拟机上工作时才重要。
如果您对当前进程可用的处理器数量感兴趣,则必须首先检查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 (AttributeError, ValueError):
pass
# Windows
try:
res = int(os.environ['NUMBER_OF_PROCESSORS'])
if res > 0:
return res
except (KeyError, ValueError):
pass
# jython
try:
from java.lang import Runtime
runtime = Runtime.getRuntime()
res = runtime.availableProcessors()
if res > 0:
return res
except ImportError:
pass
# BSD
try:
sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
stdout=subprocess.PIPE)
scStdout = sysctl.communicate()[0]
res = int(scStdout)
if res > 0:
return res
except (OSError, ValueError):
pass
# Linux
try:
res = open('/proc/cpuinfo').read().count('processor\t:')
if res > 0:
return res
except IOError:
pass
# Solaris
try:
pseudoDevices = os.listdir('/devices/pseudo/')
res = 0
for pd in pseudoDevices:
if re.match(r'^cpuid@[0-9]+$', pd):
res += 1
if res > 0:
return res
except OSError:
pass
# Other UNIXes (heuristic)
try:
try:
dmesg = open('/var/run/dmesg.boot').read()
except IOError:
dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE)
dmesg = dmesgProcess.communicate()[0]
res = 0
while '\ncpu' + str(res) + ':' in dmesg:
res += 1
if res > 0:
return res
except OSError:
pass
raise Exception('Can not determine number of CPUs on this system')
推荐文章
- 如何有效地比较两个无序列表(不是集合)?
- 如何在交互式Python中查看整个命令历史?
- 如何显示有两个小数点后的浮点数?
- 如何用OpenCV2.0和Python2.6调整图像大小
- 在每个列表元素上调用int()函数?
- 当使用代码存储库时,如何引用资源的相对路径
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?