Skip to content

Commit

Permalink
Only use available CPUs
Browse files Browse the repository at this point in the history
Not all online CPUs may be available for the current process,
especially when CPU affinity is involved. In such cases too many
threads will be created, which will unnecessarily compete for CPU
time.

Use sched_getaffinity() (if available) to determine the correct
number of threads to create.
  • Loading branch information
wsldankers committed Oct 30, 2022
1 parent f1b1b5f commit 6a9443d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion configure.ac
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ AC_SYS_LARGEFILE
AC_FUNC_MALLOC
AC_FUNC_REALLOC
AC_FUNC_STRTOD
AC_CHECK_FUNCS([memchr memmove memset strerror strtol])
AC_CHECK_FUNCS([memchr memmove memset strerror strtol sched_getaffinity])
AC_CHECK_HEADER([sys/endian.h],
[
AC_CHECK_DECLS([htole64, le64toh], [], [], [
Expand Down
23 changes: 23 additions & 0 deletions src/cpu.c
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
#define _GNU_SOURCE

#include <unistd.h>

#include "config.h"

#ifdef HAVE_SCHED_GETAFFINITY

#include <sched.h>
#include <stdio.h>

size_t num_threads(void) {
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);

if (sched_getaffinity(0, sizeof cpu_set, &cpu_set) == -1)
return sysconf(_SC_NPROCESSORS_ONLN);
else
return CPU_COUNT(&cpu_set);
}

#else

size_t num_threads(void) {
return sysconf(_SC_NPROCESSORS_ONLN);
}

#endif

0 comments on commit 6a9443d

Please sign in to comment.