I have some Matlab code which needs to be speeded up. Through profiling, I\'ve identified a particular function as the culprit in slowing down the execution. This function i
You should absolutely without any hesitation move the loop inside the mex file. The example below demonstrates a 1000 times speedup for a virtually empty work unit in a for loop. Obviously as the amount of work in the for loop changes this speedup will decrease.
Here is an example of the difference:
Mex function without internal loop:
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[ ], int nrhs, const mxArray *prhs[ ])
{
int i=1;
plhs[0] = mxCreateDoubleScalar(i);
}
Called in Matlab:
tic;for i=1:1000000;donothing();end;toc
Elapsed time is 3.683634 seconds.
Mex function with internal loop:
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[ ], int nrhs, const mxArray *prhs[ ])
{
int M = mxGetScalar(prhs[0]);
plhs[0] = mxCreateNumericMatrix(M, 1, mxDOUBLE_CLASS, mxREAL);
double* mymat = mxGetPr(plhs[0]);
for (int i=0; i< M; i++)
mymat[i] = M-i;
}
Called in Matlab:
tic; a = donothing(1000000); toc
Elapsed time is 0.003350 seconds.