ctypes number of cpus
Tuesday, November 7th, 2006#!/usr/bin/env pythonfrom ctypes import *import ctypes.utillibc = cdll.LoadLibrary(ctypes.util.find_library('libc'))def getCPUnums(): counts = {'logicalcpu': c_int(0), 'ncpu': c_int(0), 'physicalcpu': c_int(0)} for k, v in counts.iteritems(): size = c_int(sizeof(v)) libc.sysctlbyname('hw.%s' % (k,), c_voidp(addressof(v)), addressof(size), None, 0) return (int(counts['ncpu'].value), int(counts['physicalcpu'].value), int(counts['logicalcpu'].value))if __name__ == “__main__”: print “”"CPU Counts:N:\t\t%dPhysical:\t%dLogical:\t%d”"” % getCPUnums()
Of course my Intel Core 2 Duo gives me the following.
sabrina dreid:~> python cpun.pyCPU Counts:N: 2Physical: 2Logical: 2
You could have just as easily done sysctl hw.ncpu hw.physicalcpu hw.logicalcpu with commands.getoutput. But ctypes is cooler and almost certainly several times faster.