Performance of MEX versus builtin functions

55 ビュー (過去 30 日間)
Matt J
Matt J 2026 年 1 月 5 日 13:13
コメント済み: Matt J 約24時間 前
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?

回答 (1 件)

James Tursa
James Tursa 2026 年 1 月 8 日 3:34
編集済み: James Tursa 2026 年 1 月 8 日 3:36
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.
  1 件のコメント
Matt J
Matt J 約2時間 前
Thanks, James. Regarding the first point, it would surprise you then that my mex_min (attached) runs much more slowly than the native min()?
x=rand(5,1);
tic
testLoop(@min,x)
toc
tic
testLoop(@mex_min,x)
toc
Elapsed time is 0.021670 seconds.
Elapsed time is 0.947045 seconds.
function testLoop(fcn,x)
for i=1:1e6
fcn(x);
end
end

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCall C++ from MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by