MEX-file efficiency with multiple file-pass function calls in .m script

1 view (last 30 days)
If I have a script (.m-file) that calls several functions which are in separate scripts or defined at the end, I could improve its speed by in-lining my functions. If I choose to mex the main script instead I will also get a speed-up. Which is better? Further, if I inline all my function in the matlab script and then mex it, will this case be the fastest of the four cases ( .m script with file-passing functions, .m script with inlining functions, mex of file-pass script, mex of inlined script) or would it make no difference?

Answers (1)

Jan
Jan on 21 Dec 2021
Do you use the terms "function" and "script" correctly?
Functions and scripts are stored in .m-files. Functions start with the keyword "function", scripts don't.
"If I choose to mex the main script instead I will also get a speed-up" - calling a Matlab function from inside a mex function by mexCallMATLAB needs a certain overhead, so this is expensive.
There is no general decision on what is "better" or faster. It depends on the code and on the processed data. Use the profiler and tic/toc to find the bottlenecks of the code. Then improve the bottleneck, e.g. by mexing.
Remember that "speed" can mean different things. Sometimes the pure run-time is meant, but for real applications the time until a problem is solved is more important:
t_total = t_design + t_programming + t_debugging + t_documenting + t_testing + t_runtime
Write a complete code with a clean structure (e.g. avoid scripts, global variables and keep code, data and gui strictly separated) and test it. If it works reliably, use the profiler to find out, where improvements are most efficient: Accelerating some code, which takes 2% of the processing time only, can save only up to 2% of the total run-time.
Inlining all functions might be a little bit faster now, but if a multi-threaded C-mex function for a specific job is available, you have to refactor the code and test it again. Saving some seconds of run-time is not a benefit, if it costs days to modify the code.
"Premature optimization" is one of the most frequently applied pitfalls and a "programming anti-pattern".
  3 Comments
Jan
Jan on 23 Dec 2021
@SB: It depends. If you replace mean(x) by sum(x)/numel(x), the speedup is surprising. A lean version of polyfit is 20 to 60 times faster than the built-in version.
In a mexed version, the overhead of calling local M-functions is smaller, if they are included in the mex file also. But calling external M-functions is more expensive.
There I assume, that the question, which version has the sorter run-time, cannot be answered in general.
Usually optimizing the processing speed reduces the maintainability of the code, so the programmer has to find a balance.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!