Performance of MEX versus builtin functions
49 views (last 30 days)
Show older comments
When Matlab calls a MEX file, is there overhead that makes the call slower as compared to a built-in binary like min, max, etc...?
Similarly, if a MEX file calls a built-in function (via mexCallMATLAB), will it be slower to launch than if you had called the same builtin function directly from within Matlab?
0 Comments
Answers (1)
James Tursa
3 minutes ago
Edited: James Tursa
1 minute ago
I don't know the answer to your first question. But I would expect the overhead for the mex function entry (other than loading into memory) to be minimal based on how fast mex functions seem to run in practice.
For the second question, there is a gotcha. When calling functions (built-in or otherwise) from MATLAB m-files (or p-files I suppose), the normal data sharing rules seem to be in play. E.g., the reshape( ) function when acting on full variables returns some type of shared data copy. So it is relatively fast. HOWEVER, it is my belief based on past experience that mexCallMATLAB will always return deep data copies even when circumstances (such as reshape( )) could have returned some type of shared data copy. My guess is that this is a hard philosophy for mex routines. Otherwise, how would the user/programmer know when it was safe to modify the results of the call in-place? They can't, since there is no official mechanism to detect data sharing. So, in addition to the extra overhead of the mexCallMATLAB( ) call itself, there are these potential forced deep data copies that can make a function called from a mex routine much slower than calling from an m-file.
I believe the C++ interface for calling MATLAB functions operates differently. I don't use the C++ interface myself because it doesn't allow enough control of memory allocation/deallocation to my liking, but it is my impression that they attempted to imitate the lazy copy rules from the MATLAB level in this interface.
0 Comments
See Also
Categories
Find more on Call C++ from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!