Why is passing data to MEX so slow

1 次查看(过去 30 天)
jh2011
jh2011 2017-12-19
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?

回答(1 个)

Walter Roberson
Walter Roberson 2017-12-19
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.

类别

Help CenterFile Exchange 中查找有关 Write C Functions Callable from MATLAB (MEX Files) 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by