I need to pin various c/c++ processes to specific cores on a machine for benchmarking only on Windows 7 64-bit. My machine has 16 cores (2x8). I'm trying to do this by calling SetProcessAffinityMask from within the code for a given process. Assuming that's correct I am unsure of how exactly to use this function. I've seen the documentation but am unable to understand its description of what the second argument needs to be. I also haven't found any example c/c++ usage either on SO or on Google having searched.
Question1: Taking a 16 core machine (2cpux8) for example and a c/c++ project would you please provide an illustrative example for how to use SetProcessAffinityMask to pick each of the 16 cores and an explanation of the second argument for my understanding? How would I translate a core id from 0-15 to its equivalent bitmask?
Question2: Does it make a difference to the usage if there are 2x8 cores as opposed to 16 cores on one cpu? Or is it the same usage?
Many thanks. Here's what I have so far.
#include <Windows.h>
#include <iostream>
using namespace std;
int main () {
HANDLE process = GetCurrentProcess();
DWORD_PTR processAffinityMask = 0; /// What to do here?
BOOL success = SetProcessAffinityMask(process, processAffinityMask);
cout << success << endl;
return 0;
}
CPU affinity enables binding a process or multiple processes to a specific CPU core in a way that the process(es) will run from that specific core only. When trying to perform performance testing on a host with many cores, it is wise to run multiple instances of a process, each one on different core.
To set an affinity mask for Processors 3 and 7, you would set the bits as follows: You create the bitmask by enabling the bits that correspond to your processors. For example, the following code snippet shows how to enable bits for Processors 7 and 3: DWORD_PTR mask = (1<< 7) + (1<< 3);
The second parameter is a bitmask, where a bit that's set means the process can run on that proceesor, and a bit that's clear means it can't.
In your case, to have each process run on a separate core you could (for one possibility) pass a command line argument giving each process a number, and use that number inside the process to determine the processor to use:
#include <Windows.h>
#include <iostream>
using namespace std;
int main (int argc, char **argv) {
HANDLE process = GetCurrentProcess();
DWORD_PTR processAffinityMask = 1 << atoi(argv[1]);
BOOL success = SetProcessAffinityMask(process, processAffinityMask);
cout << success << endl;
return 0;
}
Then you'd run this with something like:
for %c in (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) do test %c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With