Set processor affinity for MATLAB engine (Windows 7)

前端 未结 3 949
萌比男神i
萌比男神i 2020-12-18 01:05

I\'m developing an application in c++. One of the components of the application uses Matlab (via the Matlab engine) for data processing. At the same time, a data acquisition

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-18 01:45

    Below is an implementation of the MEX function that @Praetorian described (shows how to use the SetProcessAffinityMask function):

    set_affinity.c

    #include "mex.h"
    #include 
    
    void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
    {
        HANDLE hProc;
        DWORD_PTR dwAffinityMask;
        unsigned int numCores;
    
        // check arguments
        if (nlhs > 0 || nrhs != 1) {
            mexErrMsgIdAndTxt("mex:error", "Wrong number of arguments.");
        }
        if (!mxIsDouble(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1) {
            mexErrMsgIdAndTxt("mex:error", "Expecting a scalar number.");
        }
    
        // number of logical processors
        numCores = (unsigned int) mxGetScalar(prhs[0]);
    
        // set affinity of current process to use all cores
        hProc = GetCurrentProcess();
        dwAffinityMask = (1 << numCores) - 1;
        if (!SetProcessAffinityMask(hProc, dwAffinityMask)) {
            mexErrMsgIdAndTxt("mex:error", "WinAPI error code: %lu", GetLastError());
        }
    }
    

    Example:

    On my quad-core hyper-threaded machine, I would invoke the MEX-function as following to allow MATLAB to execute on all 8 logical processors:

    >> getenv('NUMBER_OF_PROCESSORS')
    ans =
    8
    
    >> mex -largeArrayDims set_affinity.c
    >> set_affinity(8)
    

    To use only half the number of processors:

    >> set_affinity(4)
    

    Note the following remark in the MSDN doc page:

    Process affinity is inherited by any child process or newly instantiated local process.

    Do not call SetProcessAffinityMask in a DLL that may be called by processes other than your own.

    So messing with the affinity will affect all computations initiated by MATLAB and its dependent libraries. Here is a post by Raymond Chen on the topic.

提交回复
热议问题