Search code examples
matlabbenchmarkingwarm-up

Why does Matlab run faster after a script is "warmed up"?


I have noticed that the first time I run a script, it takes considerably more time than the second and third time1. The "warm-up" is mentioned in this question without an explanation.

Why does the code run faster after it is "warmed up"?

I don't clear all between calls2, but the input parameters change for every function call. Does anyone know why this is?


1. I have my license locally, so it's not a problem related to license checking.

2. Actually, the behavior doesn't change if I clear all.


Solution

  • One reason why it would run faster after the first time is that many things are initialized once, and their results are cached and reused the next time. For example in the M-side, variables can be defined as persistent in functions that can be locked. This can also occur on the MEX-side of things.

    In addition many dependencies are loaded after the first time and remain so in memory to be re-used. This include M-functions, OOP classes, Java classes, MEX-functions, and so on. This applies to both builtin and user-defined ones.

    For example issue the following command before and after running your script for the first run, then compare:

    [M,X,C] = inmem('-completenames')
    

    Note that clear all does not necessarily clear all of the above, not to mention locked functions...

    Finally let us not forget the role of the accelerator. Instead of interpreting the M-code every time a function is invoked, it gets compiled into machine code instructions during runtime. JIT compilation occurs only for the first invocation, so ideally the efficiency of running object code the following times will overcome the overhead of re-interpreting the program every time it runs.