recipes : programming : Writing better code : Why does my code run slowly?


Why does my code run really slowly? Do I need to re-write it in C or something?


This question seems to come up a lot. Most of the time, if code is running slowly there is a way to speed it up that doesn't involve C (or similar drastic measures). Slow running code can be due to a number of things. The less experience you have, the more chance there is that a simple fix can produce a big improvment in running speed. The major culprits are:

  1. Lack of pre-allocation
  2. Over-use of loops and lack of vectorising
  3. Excessive hard-disk access and .mat file loading and saving
  4. Using inefficient, "roll your own", code where optimised MATLAB functions already exist.

The links above deal with much of what you need to know. The last point boils down to the user not knowing the MATLAB language well enough. MATLAB is very powerful and it contains a lot of built-in functions. It can take a while to familiarise yourself with everything and until you do so you run the risk of (badly) re-inventing the wheel. Most tasks in MATLAB can be achieved with very few lines of code if you know which functions to use. If you have the feeling that you're writing a lot of code to do something simple, then chances are that there is a better way. With experience this will happen less but, if you need a pointer, you might look into the following functions (if you don't already know them):

Finally, a really big help will be the profview command, which is used to run MATLAB's "profiler". Arguably, this is the first thing you should turn to if your code is slow. The profiler will tell you how long each line takes to run and in some cases will suggest changes you can make. Good use of the profiler is very educational. After you have optimised everything you can think of, you might find that one of MATLAB's built in functions is what is taking most of the time. In order to be robust, MATLAB's functions contain "extra" code (such as error-checking code) which takes time to run. You may consider delving into the built-in functions (most are just .m files) and making your own, trimmed down, copies.


If you think your code is running slowly then it really pays to dig into the issue. You can often speed up code that is running too slowly, sometimes by a factor of 10 or more.