What are the best practice in mex ?
Show older comments
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.
Accepted Answer
More Answers (1)
I don't mean to sound facetious, but poorly written code will generally be slower than well written code, independently of the language it is written in. Matlab is an interpreted language. Almost by definition, interpreted languages will be slower than compiled ones, such as C/C++ (used in mex). So theres's a handicap right out of the gate.
Additionaly lower-level languages (purists will cringe when I call C++ low-level) are more flexible, will allow you to get down and dirty with your code. I guess it would be safe to say that their philosophy is you get what you pay for. In Matlab you get much more than what you pay for, which can lead to comparative slowness.
However, in Matlab there is a function for almost everything, so you will probably spend less time writing code, and more actually using it.
How to make your code faster?
That question is near impossible to answer without looking at your code. There are very many possible answers. A generic piece of advice would be: use a profiler, see what are the most demanding parts of your code and focus on improving those. Blind optimization might be, at best, a waste of time and could actually make your code slower.
The compiler will most definitely impact speed. Which one will work better? Hard to say. You should test different ones.
Categories
Find more on Execution Speed in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!