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
If you're interested into the number of processors available to your current process, you have to check cpuset first. Otherwise (or if cpuset is not in use),
multiprocessing.cpu_count()
is the way to go in Python 2.6 and newer. The following method falls back to a couple of alternative methods in older versions of Python:If you have python with a version >= 2.6 you can simply use
http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count
platform independent:
https://github.com/giampaolo/psutil/blob/master/INSTALL.rst
Can't figure out how to add to the code or reply to the message but here's support for jython that you can tack in before you give up:
len(os.sched_getaffinity(0))
is what you usually wanthttps://docs.python.org/3/library/os.html#os.sched_getaffinity
os.sched_getaffinity(0)
(added in Python 3) returns the set of CPUs available considering thesched_setaffinity
Linux system call, which limits which CPUs a process and its children can run on.0
means to get the value for the current process. The function returns aset()
of allowed CPUs, thus the need forlen()
.multiprocessing.cpu_count()
on the other hand just returns the total number of physical CPUs.The difference is especially important because certain cluster management systems such as Platform LSF limit job CPU usage with
sched_getaffinity
.Therefore, if you use
multiprocessing.cpu_count()
, your script might try to use way more cores than it has available, which may lead to overload and timeouts.We can see the difference concretely by restricting the affinity with the
taskset
utility.For example, if I restrict Python to just 1 core (core 0) in my 16 core system:
with the test script:
main.py
then the output is:
nproc
however does respect the affinity by default and:outputs:
and
man nproc
makes that quite explicit:nproc
has the--all
flag for the less common case that you want to get the physical CPU count:The only downside of this method is that this appears to be UNIX only. I supposed Windows must have a similar affinity API, possibly
SetProcessAffinityMask
, so I wonder why it hasn't been ported. But I know nothing about Windows.Tested in Ubuntu 16.04, Python 3.5.2.
You can also use "joblib" for this purpose.
This method will give you the number of cpus in the system. joblib needs to be installed though. More information on joblib can be found here https://pythonhosted.org/joblib/parallel.html
Alternatively you can use numexpr package of python. It has lot of simple functions helpful for getting information about the system cpu.