Matlab: Does calling the same mex function repeatedly from a loop incur too much overhead?

后端 未结 3 895
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 00:30

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

3条回答
  •  醉话见心
    2021-01-18 01:20

    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.
    

提交回复
热议问题