|
[See Speed MATLAB by optimizing memory access for tips on optimizing memory-bound code.]
MATLAB is great tool for algorithm development. It provides a simple programming environment with an extensive library of functions to help develop, analyze and visualize complex algorithms. However, MATLAB is sometimes slow, which limits its usefulness.
This article gives a quick overview of the different techniques available for speeding up MATLAB code. It covers the basics of performance profiling, vectorization, and turning MATLAB code into compiled MEX-files.
What slows MATLAB down?
MATLAB is an interpreted language. This means each operation carries an additional overhead not found in compiled languages such as C or C++. (Note: MATLAB includes just-in-time (JIT) machine code creation which alleviates this problem in limited instances).
For every single operation in MATLAB, the interpreter has to look at the operands involved and select the correct computation to perform. This selection is based on the base data types (double real, complex, char, logical, etc.) and shapes (scalar, row, column, matrix, etc.) of the operands. Once the operations are completed, the resulting values need to be stored. For every single assignment, the MATLAB interpreter has to look at both input and output operands and decide if more memory needs to be allocated or if values need to be converted in the assignment.
This selection and assignment overhead is the main reason MATLAB is slower than compiled languages. The interpreter overhead is especially significant when your operations are performed on scalars or small sets of data. This helps explain why scalar-based loops are notoriously slow in MATLAB.
Profile your code
The typical rule for accelerating code is to optimize where it matters. If you spend 80% of your run-time on 20 lines of code or in one function, then this is where you want to focus your effort.
The MATLAB Profiler tool that is built into MATLAB is a great way to find performance bottlenecks in your code. This easy-to-use tool can be called from the command line using the profile command or from the MATLAB desktop using Desktop > Profiler. For a given run, the profiler viewer allows you to navigate between functions and browse through the code, allowing you to quickly find where most of your time is spent.
As an example, the screen shots below show the MATLAB profiler report for a block-matching algorithm used for motion estimation. Looking at the profile, it is quickly evident that most of the run-time is spent in the costFunctionMAD function. As one might expect, a look inside this function reveals that the hot-spot is the computation of mean absolute difference between two blocks.

(Click to enlarge)
|