I want to know the number of CPUs on the local machine using Python. The result should be user/real
as output by time(1)
when called with an optimally scaling userspace-only program.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
These give you the hyperthreaded CPU count
multiprocessing.cpu_count()
os.cpu_count()
These give you the virtual machine CPU count
psutil.cpu_count()
numexpr.detect_number_of_cores()
Only matters if you works on VMs.
Another option if you don't have Python 2.6:
Another option is to use the
psutil
library, which always turn out useful in these situations:This should work on any platform supported by
psutil
(Unix and Windows).Note that in some occasions
multiprocessing.cpu_count
may raise aNotImplementedError
whilepsutil
will be able to obtain the number of CPUs. This is simply becausepsutil
first tries to use the same techniques used bymultiprocessing
and, if those fail, it also uses other techniques.multiprocessing.cpu_count()
will return the number of logical CPUs, so if you have a quad-core CPU with hyperthreading, it will return8
. If you want the number of physical CPUs, use the python bindings to hwloc:hwloc is designed to be portable across OSes and architectures.
In Python 3.4+: os.cpu_count().
multiprocessing.cpu_count()
is implemented in terms of this function but raisesNotImplementedError
ifos.cpu_count()
returnsNone
("can't determine number of CPUs").This may work for those of us who use different os/systems, but want to get the best of all worlds: