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

Nick Craig-Wood nick at craig-wood.com
Fri Oct 5 06:30:12 EDT 2007


Nicholas Bastin <nick.bastin at gmail.com> wrote:
>  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.

On any unix/posix system (OSX and linux should both qualify) you can use

  >>> import os
  >>> os.sysconf('SC_NPROCESSORS_ONLN')
  2
  >>>

(From my Core 2 Duo laptop running linux)

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list