The following is the implementation of the MEX function described by @Praetorian (shows how to use the SetProcessAffinityMask function ):
set_affinity.c
#include "mex.h" #include <windows.h> 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-threading machine, I would call the MEX function as follows so that MATLAB could 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 note in the MSDN document page :
A process affinity is inherited by any child process or a local process created.
Do not call SetProcessAffinityMask in a DLL that may be caused by processes other than your own.
Thus, communication with affinity will affect all calculations initiated by MATLAB and its dependent libraries. Here is Raymond Chen 's post on the topic.
Amro
source share