What is the difference in running time if
replaced with its value in the code on the left?
function test (n, runs) range = 1:n; for r = 1:runs for i = range j = i * i; end end
function test (n, runs) for r = 1:runs for i = 1:n j = i * i; end end
Intuitively, we would think the code on the right should be a bit
1:n has to be analyzed many times. However,
on my Linux box with MATLAB 6.5 (R13sp1),
takes ~7.5 seconds with the code on the left, and ~0.09 seconds with
the code on the right.
The reason is MATLAB 6.5 (R13) has introduced JIT-Accelerator as a
new performance optimization tool, which can optimize
loops if the loop expression is in the form of
although the code below introduces more extra operations, it still runs
faster (~0.14 seconds) than the code on the left.
function test (n, runs) range = 1:n; for r = 1:runs for t = 1:length(range), i = range(t); j = i * i; end end
Here is a nice introductory article on the MATLAB profiler and the JIT-Accelerator. And here are some sample accelerated programs.