Search code examples
c++matlabmatrixmex

Why is passing data from MATLAB to mex so slow?


I have created this MEX function that takes in arguments like this:

toSolve(domain, model.one, model.two, model.three, model.four, bc, model.T, model.dt, [start model.five])

Where model is a MATLAB struct with matrices one,two,three,five, and a 1x3 cell four that has three matrices.

The matrices are huge (~500,000 x 3) each. When I pass the data into the mex function (i.e. toSolve), it takes forever to load. In my mex function, the first line is a printout:

void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{

/* Start */
mexPrintf("\n About to start");

//CODE//

}

It takes forever to print that line About to start. The code itself runs very quickly. I'm not sure why it takes forever to pass the data into mex? What did I do wrong?


Solution

  • Its probably your computation that takes the time, and the reason you don't see the print statement quickly is due to the buffer not being force flushed (i.e. do the actual writing to screen). See this question and answers for some more info.

    In short if you add:

    mexEvalString("drawnow;")
    

    after the mexPrintf command. If you see the text written to the screen quickly and that should help you confirm if its the calculation that takes time not the passing data into MEX.