MATLAB: Improving code performance by compiling

MATLABmatlab coderMATLAB Compiler

Hello,
I'm coding a program where runtime is relevant, so I'm looking for ways to optimize performance. From what I've read here
the compiler / compiler SDK (don't really know the difference between the two) can create standalone apps that support most features – including graphics – but does not speed up the code since it is not compiled. The coder on the other hand can improve runtime, but does not support graphics (which I need). So in my case the only way to make use of compilation to speed up the program would be to put code into functions wherever possible and then compile those into mex files. Is that right?

Best Answer

Optimization of code is done in different steps:
  1. Write the code as clean and clear as possible. Do not start with a pre-mature optimization, because this is too prone to bugs.
  2. Prove that the code is working correctly using unit- or integration tests.
  3. Then you have a start point to compare the results with the improved versions.
  4. Use the profiler to find the bottlenecks. It is not worth to optimize a piece of code, which needs 1% of the processing time only.
  5. In many situations investing some brain power can accelerate the code massively: Process matrices columnwise instead of rowwise, move repeated code out of loops, avoid creating variables dynamically by EVAL, or LOAD without storing the output in a variable. Maths can be useful also e.g. by reducing the number of expensive EXP or POWER functions.
  6. Rewriting the bottlenecks as C-Mex functions can be very efficient, but if e.g. the amin work is spend in linear algebra routines, Matlab uses highly optimized libraries already.
  7. If rewriting the code as C-Mex is to expensive, try the Coder. This converts the code automatically but with some overhead compared to a manually written C-Mex function.
  8. If graphics are the bottleneck, there is no solution. Matlab 2009a was much faster for a lot of tasks, and the 20 year old Matlab 6.5 beat them all, because it did not use Java for the rendering. But of course the ancient Matlab versions have many drawbacks also - if you want a box around a diagram, you have to rotate the diagram by 0.0001 degreem if OpenGL is used as renderer...
After the optimization is ready, compare the results with the initial version. Compiled functions and even C-Mex functions need not be compatible with future versions, so care for keeping the original not optimized M-files.
Compiling can accelerate your code by a factor 2, with some luck. Exploiting the underlying maths and improving the MATLAB code can give you a fctor of 100. You find some examples in the forum with 200 and 1000 times faster code in pure Matlab. So maybe it is worth to share the code of the bottlenecks of your code.