Python获得CPU核数的方法
准确来说,获得的不是核心(Core)数,而是并发的线程数。在multiprocessing模块中的cpu_count()函数已经实现了该功能,函数的源码如下:
def cpu_count(): ''' Returns the number of CPUs in the system ''' if sys.platform == 'win32': #我很好奇64bit的windows是不是也是win32 try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 elif 'bsd' in sys.platform or sys.platform == 'darwin': comm = '/sbin/sysctl -n hw.ncpu' if sys.platform == 'darwin': comm = '/usr' + comm try: with os.popen(comm) as p: num = int(p.read()) except ValueError: num = 0 else: try: num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: return num else: raise NotImplementedError('cannot determine number of cpus')
如果是Windows环境,则从环境变量NUMBER_OF_PROCESSORS中得到CPU线程数量;如果是BSD或者Mac OS,则是执行sysctl -n hw.ncpu(注意Mac OS的是在/usr/sbin/sysctl -n hw.ncpu中);如果是其他系统(一般就剩下Linux了),则执行os.sysconf('SC_NPROCESSORS_ONLN')得到。