MATLAB: What are the best practice in mex

mexmex compiler

I have written a code in MEX to check its speed against the fully vectorized m-files. My codes are slower than m-files. My question is how to make it faster. I have always seen people writing comments like a nicely written mex file to be faster than m-file. But how is mex files nicely written. Time to access pointers or using global variable what are the things which affects its speed.
In case you need code let me know its quite large around 2000 lines. Does the choice of compiler affect its speed. I am using linux and using mcc to build the mex files.

Best Answer

Write efficient C-code is definitively a very important and interesting question, which should be answered in a forum about C.
Some good programming methods concern C as well as Matlab:
  • In nested loops, move the ones with more iterations to the inside. This reduces the overhead for starting loops.
  • Access memory in contiguos blocks: While X(:, 1) can be copied efficiently because Matlab stores the elements in column order, reading or writing X(1, :) is much more expensive.
  • Avoid repeated calculations. Store them in a temporary variable instead.
  • Divide large problems into chunks, which match in the processor cache.
  • Use optimized libraries for linear algebra. Programming e.g. a matrix multiplication is a really bad idea.
  • Program clean and clear at first. Debugging is more important than a runtime optimization. Optimizing the code is the last step of the programming process.
  • A well design is the basement of a well implementation. So start a large projekt (I guess that 2000 lines of code are "large" already) at least with pencil and paper, not in the editor. Inserting features afterwards will usually lead to spaghetti-code.