Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
966 views
in Technique[技术] by (71.8m points)

windows - Example usage of SetProcessAffinityMask in C++?

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;

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...