MATLAB: Implausible execution times

jitMATLABtic toc

I teach a university course on numerical methods and MATLAB. I assigned my students to evaluate the execution times for various operations. Specifically, I had them compare the following two cases:
format short
tic
for i=1:1000
for j=1:1000
for k=1:1000
x=k;
end
end
end
toc
versus this:
format short
tic
for i=1:1000
for j=1:1000
for k=1:1000
x=j+k;
end
end
end
toc
The second code with the added addition operation reproducibly takes significantly (~30%) less execution time than the first. This seemingly implausible result appears to occur in version R2011b and not earlier versions (although I haven't done an exhaustive test). Any explanation for this? (BTW, the same result holds if the addition is replaced by a multiplication).

Best Answer

J I T - Matlab's magic, efficient and poorly documented JustInTime accelerator can understand some loop constructions. Then the performance can be increases dramatically in some cases, e.g. in your 2nd example. When the loop contents does not match to a pattern recognized by the JIT, or if some external functions are included, the JIT looses its power.
Try to measure the speed with a disabled JIT:
feature('jit', 'off')
feature('accel', 'off')
I'm not sure, if these are synonyms.
Another way to disable the JIT is setting a breakpoint (behind the toc - otherwise the timings are not usable) or starting the profiler. The later is a serious problem, because the results of the profiler are not really useful without considering the effects of the JIT. Debugging and profiling must collide with the JIT, because these procedure require a line-by-line procesing of the code - but the JIT can combine or re-order lines to increase the efficiency.