Skip to content

Commit 0c91023

Browse files
committed
Honor CPU affinity in ThreadPool::getNumCores
This reports that number of CPUs that are actually usable by the current process. This means that I can do something like `taskset -c 0 emcc hello.c -O2` and the internal call to `wasm-opt` within emcc will only use a single core. Ideally this would work on macOS and windows too, but I'm not even sure how easy it is to control affinity on those OSes.
1 parent 36366d2 commit 0c91023

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

src/support/threads.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
#include <iostream>
2121
#include <string>
2222

23+
#ifdef __linux__
24+
#include <sched.h> // For sched_getaffinity
25+
#endif
26+
2327
#include "compiler-support.h"
2428
#include "threads.h"
2529
#include "utilities.h"
@@ -145,6 +149,18 @@ size_t ThreadPool::getNumCores() {
145149
return 1;
146150
#else
147151
size_t num = std::max(1U, std::thread::hardware_concurrency());
152+
#ifdef __linux__
153+
// On linux we can do better since we can get the number of CPU that are
154+
// actually usable by the current process.
155+
cpu_set_t cpu_set;
156+
CPU_ZERO(&cpu_set);
157+
if (sched_getaffinity(0, sizeof(cpu_set), &cpu_set) == 0) {
158+
num = 0;
159+
for (int i = 0; i < CPU_SETSIZE; i++) {
160+
if (CPU_ISSET(i, &cpu_set)) num++;
161+
}
162+
}
163+
#endif
148164
if (getenv("BINARYEN_CORES")) {
149165
num = std::stoi(getenv("BINARYEN_CORES"));
150166
}

0 commit comments

Comments
 (0)