Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 208
Stewie Griffin Avatar asked Jun 01 '13 14:06

Stewie Griffin


People also ask

Is Matlab live script slower?

It's still extremely slow. Not only the execution but the input/scrolling as well.

Are functions faster than scripts Matlab?

Use functions instead of scripts. Functions are generally faster.


2 Answers

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.

like image 82
Amro Avatar answered Sep 20 '22 23:09

Amro


Matlab is interpreted. If you don't warm up the code, you will be losing a lot of time due to interpretation instead of the actual algorithm. This can skew results of timings significantly.

Running the code at least once will enable Matlab to actually compile appropriate code segments.

like image 40
Marc Claesen Avatar answered Sep 21 '22 23:09

Marc Claesen