@@ -113,6 +113,18 @@ corresponding Unix manual entries for more information on calls.");
113113#include <dlfcn.h>
114114#endif
115115
116+ #ifdef __hpux
117+ #include <sys/mpctl.h>
118+ #endif
119+
120+ #if defined(__DragonFly__ ) || \
121+ defined(__OpenBSD__ ) || \
122+ defined(__FreeBSD__ ) || \
123+ defined(__NetBSD__ ) || \
124+ defined(__APPLE__ )
125+ #include <sys/sysctl.h>
126+ #endif
127+
116128#if defined(MS_WINDOWS )
117129# define TERMSIZE_USE_CONIO
118130#elif defined(HAVE_SYS_IOCTL_H )
@@ -10302,6 +10314,60 @@ get_terminal_size(PyObject *self, PyObject *args)
1030210314}
1030310315#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
1030410316
10317+ PyDoc_STRVAR (posix_cpu_count__doc__ ,
10318+ "cpu_count() -> integer\n\n\
10319+ Return the number of CPUs in the system, or None if this value cannot be\n\
10320+ established." );
10321+
10322+ #if defined(__DragonFly__ ) || \
10323+ defined(__OpenBSD__ ) || \
10324+ defined(__FreeBSD__ ) || \
10325+ defined(__NetBSD__ ) || \
10326+ defined(__APPLE__ )
10327+ static long
10328+ _bsd_cpu_count (void )
10329+ {
10330+ long ncpu = 0 ;
10331+ int mib [2 ];
10332+ size_t len = sizeof (int );
10333+
10334+ mib [0 ] = CTL_HW ;
10335+ mib [1 ] = HW_NCPU ;
10336+ if (sysctl (mib , 2 , & ncpu , & len , NULL , 0 ) == 0 )
10337+ return ncpu ;
10338+ else
10339+ return 0 ;
10340+ }
10341+ #endif
10342+
10343+ static PyObject *
10344+ posix_cpu_count (PyObject * self )
10345+ {
10346+ long ncpu = 0 ;
10347+ #ifdef MS_WINDOWS
10348+ SYSTEM_INFO sysinfo ;
10349+ GetSystemInfo (& sysinfo );
10350+ ncpu = sysinfo .dwNumberOfProcessors ;
10351+ #elif defined(__hpux )
10352+ ncpu = mpctl (MPC_GETNUMSPUS , NULL , NULL );
10353+ #elif defined(HAVE_SYSCONF ) && defined(_SC_NPROCESSORS_ONLN )
10354+ ncpu = sysconf (_SC_NPROCESSORS_ONLN );
10355+ #elif defined(__APPLE__ )
10356+ size_t len = sizeof (int );
10357+ if (sysctlnametomib ("hw.logicalcpu" , & ncpu , & len , NULL , 0 ) != 0 )
10358+ ncpu = _bsd_cpu_count ();
10359+ #elif defined(__DragonFly__ ) || \
10360+ defined(__OpenBSD__ ) || \
10361+ defined(__FreeBSD__ ) || \
10362+ defined(__NetBSD__ )
10363+ ncpu = _bsd_cpu_count ();
10364+ #endif
10365+ if (ncpu >= 1 )
10366+ return PyLong_FromLong (ncpu );
10367+ else
10368+ Py_RETURN_NONE ;
10369+ }
10370+
1030510371
1030610372static PyMethodDef posix_methods [] = {
1030710373 {"access" , (PyCFunction )posix_access ,
@@ -10747,6 +10813,8 @@ static PyMethodDef posix_methods[] = {
1074710813#if defined(TERMSIZE_USE_CONIO ) || defined (TERMSIZE_USE_IOCTL )
1074810814 {"get_terminal_size" , get_terminal_size , METH_VARARGS , termsize__doc__ },
1074910815#endif
10816+ {"cpu_count" , (PyCFunction )posix_cpu_count ,
10817+ METH_NOARGS , posix_cpu_count__doc__ },
1075010818 {NULL , NULL } /* Sentinel */
1075110819};
1075210820
0 commit comments