Cross platform way of finding number of processors on a machine?

Nicholas Bastin nick.bastin at gmail.com
Fri Oct 5 00:02:43 EDT 2007


On 10/4/07, John <weekender_ny at yahoo.com> wrote:
>
> Is there a way to find the number of processors on a machine (on linux/
> windows/macos/cygwin) using python code (using the same code/cross
> platform code)?

There's no single call that will give you the same info on every
platform, but you can obviously write this yourself and switch based
on os.uname()[0] in most cases.

For Darwin, you can just use the subprocess module to call 'sysctl
hw.logicalcpu'.  I'm not sure if there's a more direct way in python
to use sysctl.  (hw.logicalcpu_max is what the hardware maximally
supports, but someone may have started their machine with OF blocking
some of the processors and you should probably respect that decision)

For Linux you can read /proc/cpuinfo and parse that information.  Be
somewhat careful with this, however, if your processors support HT,
they will show as 2, and that may or may not be what you want.  You
can deterministically parse this information out if you know which
processor families are truly multi-core, and which are HT.

For Win32, the cheap and dirty way is to read the NUMBER_OF_PROCESSORS
environment variable.  99% of the time, this will be correct, so it
might be sufficient for your purposes.  There is a system call
available on windows that will net you the true number of virtual
cpus, but I don't know what it is.

I don't have a cygwin install laying around, but my guess is there's a
sysctl option there too.

One note:  *all* of these methods will tell you the virtual number of
CPUs in a machine, not the physical number.  There's almost no reason
why you care about the distinction between these two numbers, but if
you do, you'll have to go to great lengths to probe the actual
hardware on each platform.  (And pre-WinXP, Windows doesn't actually
know the difference - all processors are presumed to be physical).

Also, Darwin and Linux will easily allow you to get the speed of the
processors, but on x86 these numbers are not the maximums due to C1E
and EIST (x86 processors from all vendors are capable of changing
speeds depending on load).

--
Nick



More information about the Python-list mailing list