Example usage of SetProcessAffinityMask in C++?

前端 未结 2 956
情话喂你
情话喂你 2020-12-09 04:42

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 call

相关标签:
2条回答
  • 2020-12-09 05:14

    As already mentioned, it's a bitmask. You may want to use the result of GetProcessAffinityMask, incase your process or system doesn't have access to all the cores already. Here's what I came up with.

    #include <Windows.h>
    #include <iostream>
    using namespace std; 
    
    int main () { 
    
        HANDLE process = GetCurrentProcess(); 
    
        DWORD_PTR processAffinityMask;
        DWORD_PTR systemAffinityMask;
    
        if (!GetProcessAffinityMask(process, &processAffinityMask, &systemAffinityMask))
            return -1;
    
        int core = 2; /* set this to the core you want your process to run on */
        DWORD_PTR mask=0x1;
        for (int bit=0, currentCore=1; bit < 64; bit++)
        {
            if (mask & processAffinityMask)
            {
                if (currentCore != core)
                {
                    processAffinityMask &= ~mask;
                }
                currentCore++;
            }
            mask = mask << 1;
        }
    
        BOOL success = SetProcessAffinityMask(process, processAffinityMask); 
    
        cout << success << endl; 
    
        return 0; 
    
    } 
    
    0 讨论(0)
  • 2020-12-09 05:34

    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
    
    0 讨论(0)
提交回复
热议问题