How to use core affinity to pin a process to a core on Windows using C/C++

Here’s how you can use core affinity to pin a particular process to any given core in C/C++ on Windows. The program below works by receiving the core number to pin the process to as the first argument to the executable. So for the first core you’d pass 0, for core 16 you’d pass 15 and so on.

[cpp]
#include <windows.h>
#include <iostream>
#include <algorithm>

using namespace std;

int main (int argc, char **argv) {

// pin process to a core requested by incoming argument
BOOL result = SetProcessAffinityMask(GetCurrentProcess(), 1 << atoi(argv[1]));
if (result == 0) { cout << "SetProcessAffinityMask failed" << endl; return -1; }

// perform long running cpu computation
for (int i = 0; i < 10; i++) {

// create a large array
int sampleSize = 100000000;
int* randoms = new int[sampleSize];
for (int i = 0; i < sampleSize; i++) {
randoms[i] = rand();
}

// sort it to take up some cpu time
sort(randoms, randoms + sizeof randoms / sizeof randoms[0]);

// cleanup
delete[] randoms;

}

return 0;

}
[/cpp]

The line of interest that actually applies core affinity is below.

[cpp]
BOOL result = SetProcessAffinityMask(GetCurrentProcess(), 1 << atoi(argv[1]));
[/cpp]

There’s one thing you should watch out for when using core affinity. If you run a long running computation like the one above and you’re checking which cores get spiked on task manager > performance like I was you may see that more than one core gets spiked and you may initially think that the core affinity is not working. However this is a red herring as I explain below.

You’ll notice that other cores will suffer small spikes but only one core (the one you are pinning to) will sustain load the entire duration of the computation. So what’s actually happening is that in the initial period when your program is being set up to run other cores are getting involved but for the execution of your program only the requested core is being used. So always make sure that the computation runs long enough for you to see which one runs under sustained load.

One thought on “How to use core affinity to pin a process to a core on Windows using C/C++

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s