insights on how the matlab interpreter works

There is a difference running code by copy-pasting into the command line, or inside a function. I see:

Elapsed time is 0.062195 seconds.
Elapsed time is 0.034381 seconds.

when copy-pasting in the command line, and

Elapsed time is 0.024922 seconds.
Elapsed time is 0.025392 seconds.

if I create a function M-file with that same code in it and run the function (a function M-file has a line starting with the function keyword as the first non-comment line). In this case, the two loops are equally fast (the first one might be slightly faster, but the difference is small).

You’ll also notice that both loops run faster than when copy-pasting in the command line. When running a function, the function is compiled and then executed (this is referred to as “just-in-time compilation”, or JIT). This compiler is able to optimize out the multiple indexing operations, effectively indexing only once.

On the command line, no compilation occurs, and therefore the index location is computed five times, and the value is retrieved five times.

Script M-files (M-files that do not start with the function keyword) are supposed to get JIT-compiled, but this doesn’t always seem to happen, at least not with the same amount of optimizations.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top