MEX-file efficiency with multiple file-pass function calls in .m script
2 views (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?
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".