From af94ba2dfbd9f195bc39127c12b1844f248335fb 2008-06-24 00:29:58 From: Fernando Perez Date: 2008-06-24 00:29:58 Subject: [PATCH] Add num_cpus() functions to detect total number of CPUs active. --- diff --git a/IPython/genutils.py b/IPython/genutils.py index 2cc19c0..4bc418d 100644 --- a/IPython/genutils.py +++ b/IPython/genutils.py @@ -27,9 +27,11 @@ try: except ImportError: pass import os +import platform import re import shlex import shutil +import subprocess import sys import tempfile import time @@ -2041,6 +2043,55 @@ def wrap_deprecated(func, suggest = ''): stacklevel = 2) return func(*args, **kwargs) return newFunc - -#*************************** end of file ********************** + +def _num_cpus_unix(): + """Return the number of active CPUs on a Unix system.""" + return os.sysconf("SC_NPROCESSORS_ONLN") + + +def _num_cpus_darwin(): + """Return the number of active CPUs on a Darwin system.""" + p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) + return p.stdout.read() + + +def _num_cpus_windows(): + """Return the number of active CPUs on a Windows system.""" + return os.environ.get("NUMBER_OF_PROCESSORS") + + +def num_cpus(): + """Return the effective number of CPUs in the system as an integer. + + This cross-platform function makes an attempt at finding the total number of + available CPUs in the system, as returned by various underlying system and + python calls. + + If it can't find a sensible answer, it returns 1 (though an error *may* make + it return a large positive number that's actually incorrect). + """ + + # Many thanks to the Parallel Python project (http://www.parallelpython.com) + # for the names of the keys we needed to look up for this function. This + # code was inspired by their equivalent function. + + ncpufuncs = {'Linux':_num_cpus_unix, + 'Darwin':_num_cpus_darwin, + 'Windows':_num_cpus_windows, + # On Vista, python < 2.5.2 has a bug and returns 'Microsoft' + # See http://bugs.python.org/issue1082 for details. + 'Microsoft':_num_cpus_windows, + } + + ncpufunc = ncpufuncs.get(platform.system(), + # default to unix version (Solaris, AIX, etc) + _num_cpus_unix) + + try: + ncpus = max(1,int(ncpufunc())) + except: + ncpus = 1 + return ncpus + +#*************************** end of file **********************