Python を使用して、ローカル マシンの CPU の数を知りたいです。結果は、最適にスケーリングされたユーザー空間のみのプログラムで呼び出さuser/realれた場合の出力と同じである必要があります。time(1)
15 に答える
バージョン>= 2.6のpythonを使用している場合は、単に使用できます
import multiprocessing
multiprocessing.cpu_count()
http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count
現在のプロセスで使用できるプロセッサの数に関心がある場合は、最初に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')
別のオプションは、psutilライブラリを使用することです。これは、次のような状況で常に役立ちます。
>>> import psutil
>>> psutil.cpu_count()
2
psutilこれは、 (Unix および Windows) でサポートされているすべてのプラットフォームで動作するはずです。
場合multiprocessing.cpu_countによっては、CPU の数を取得できるまでNotImplementedErrorしばらく時間がかかることがあります。psutilこれは単純に、 が でpsutil使用されているのと同じ手法を最初に使用しようとしmultiprocessing、それらが失敗した場合は他の手法も使用するためです。
Python 3.4 以降: os.cpu_count()。
multiprocessing.cpu_count()この関数に関して実装されていますが、返されたNotImplementedError場合に発生します(「CPU の数を特定できません」)。os.cpu_count()None
物理コア (仮想ハイパースレッド コアではない) の数を知りたい場合は、プラットフォームに依存しないソリューションを次に示します。
psutil.cpu_count(logical=False)
https://github.com/giampaolo/psutil/blob/master/INSTALL.rst
のデフォルト値logicalはTrueであることに注意してください。したがって、ハイパースレッド コアを含めたい場合は、次を使用できます。
psutil.cpu_count()
os.cpu_count()これは とと同じ数を与えますがmultiprocessing.cpu_count()、どちらもlogicalキーワード引数を持っていません。
multiprocessing.cpu_count()は論理 CPU の数を返すため、ハイパースレッディングを備えたクアッドコア CPU を使用している場合は を返し8ます。物理 CPU の数が必要な場合は、hwloc への python バインディングを使用します。
#!/usr/bin/env python
import hwloc
topology = hwloc.Topology()
topology.load()
print topology.get_nbobjs_by_type(hwloc.OBJ_CORE)
hwloc は、OS やアーキテクチャ間で移植できるように設計されています。
コードに追加する方法やメッセージに返信する方法がわかりませんが、あきらめる前に追加できる jython のサポートは次のとおりです。
# jython
try:
from java.lang import Runtime
runtime = Runtime.getRuntime()
res = runtime.availableProcessors()
if res > 0:
return res
except ImportError:
pass
この目的で「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()
トーチを使用している場合は、次のことができます。
import torch.multiprocessing as mp
mp.cpu_count()
torch の mp ライブラリには、メインの python ライブラリと同じインターフェイスがあるため、コメンターが言及したように、これも実行できます。
python -c "import multiprocessing; print(multiprocessing.cpu_count())"
お役に立てれば!;) 複数のオプションがあると便利です。