Why is passing data to MEX so slow

1 view (last 30 days)
jh2011
jh2011 on 19 Dec 2017
Answered: Walter Roberson on 19 Dec 2017
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?

Answers (1)

Walter Roberson
Walter Roberson on 19 Dec 2017
If you had assigned the same content to two different variables, such as
params_one = .....
model.one = params_one;
without modifying either one of those before the mex call, then at the time of the assignment, MATLAB does not make a copy of the data: instead it just creates two different symbol table entries and points both of them to the same data, setting the "reference count" to one for each variable it has been assigned to. Then you pass the variable into the MEX routine, MATLAB must sometimes assume that your mex routine might modify the data. In such a case, it needs to break the connection between the two variables pointing to the same block, which it does by making a second copy of the data, changing its reference count to one, and decrementing the reference count by one on the old block. There are some circumstances where it can prove that it does not need to do this kind of copying and then it does not bother to do so.
I suspect that you are seeing the time required to make those copies of shared blocks of data, which are done because of MATLAB's "copy on write" use of variables.

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!