commit 336affe9277fd0dee1d6bec028bb17f080a841af Author: Campbell Barton Date: Sun Oct 10 10:16:47 2021 +1100 Support accessing the number of processors Add (processor-count) for accessing the number of cores/CPU's. diff --git a/src/emacs.c b/src/emacs.c index 866e43fda9..5715325ffe 100644 --- a/src/emacs.c +++ b/src/emacs.c @@ -3156,6 +3156,15 @@ DEFUN ("daemon-initialized", Fdaemon_initialized, Sdaemon_initialized, 0, 0, 0, return Qt; } +DEFUN ("processor-count", Fprocessor_count, Sprocessor_count, 0, 0, 0, + doc: /* Return the number of processors on this system. + +The value will always be above zero, 1 for unsupported systems. */) + (void) +{ + return make_fixnum (get_processor_count()); +} + void syms_of_emacs (void) { @@ -3176,6 +3185,7 @@ syms_of_emacs (void) defsubr (&Sinvocation_directory); defsubr (&Sdaemonp); defsubr (&Sdaemon_initialized); + defsubr (&Sprocessor_count); DEFVAR_LISP ("command-line-args", Vcommand_line_args, doc: /* Args passed by shell to Emacs, as a list of strings. diff --git a/src/lisp.h b/src/lisp.h index 480c389a3b..b74bcae7fb 100644 --- a/src/lisp.h +++ b/src/lisp.h @@ -4618,6 +4618,7 @@ maybe_disable_address_randomization (int argc, char **argv) extern EMACS_INT get_random (void); extern void seed_random (void *, ptrdiff_t); extern void init_random (void); +extern int get_processor_count (void); extern void emacs_backtrace (int); extern AVOID emacs_abort (void) NO_INLINE; extern int emacs_fstatat (int, char const *, void *, int); diff --git a/src/sysdep.c b/src/sysdep.c index 8eaee22498..a46e3ce200 100644 --- a/src/sysdep.c +++ b/src/sysdep.c @@ -2182,6 +2182,38 @@ get_random (void) return val & INTMASK; } +/* + * Return the number of CPU's / cores (>= 1). + */ +int +get_processor_count (void) +{ + int nproc = -1; +#ifdef WINDOWSNT + SYSTEM_INFO info; + GetSystemInfo(&info); + nproc = (int)info.dwNumberOfProcessors; +#elif defined (HW_NCPUONLINE) || defined (HW_NCPU) + int mib[2]; + size_t len; + + mib[0] = CTL_HW; +# ifdef HW_NCPUONLINE + mib[1] = HW_NCPUONLINE; +# else + mib[1] = HW_NCPU; +# endif + len = sizeof nproc; + sysctl(mib, 2, &nproc, &len, NULL, 0); +#elif defined (__hpux) + nproc = mpctl(MPC_GETNUMSPUS, NULL, NULL); +#elif defined (_SC_NPROCESSORS_ONLN) + nproc = (int)sysconf(_SC_NPROCESSORS_ONLN); +#endif + + return (nproc > 0) ? nproc : 1; +} + #ifndef HAVE_SNPRINTF /* Approximate snprintf as best we can on ancient hosts that lack it. */ int