MATLAB Tips

Loop Expression

What is the difference in running time if range is 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 slower since 1:n has to be analyzed many times. However, on my Linux box with MATLAB 6.5 (R13sp1), test(200,10000) 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 for loops if the loop expression is in the form of M:N:P. Thus 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
Be aware: this code runs really slow in MATLAB 6.0 (R12) without the JIT-Accelerator, ~12.57 seconds.

Here is a nice introductory article on the MATLAB profiler and the JIT-Accelerator. And here are some sample accelerated programs.