Fred S
Fred S

Reputation: 1511

MATLAB: Nested for-loop takes longer every successive iteration

/edit: The loop doesn't become slower. I didn't take the time correctly. See Rasman's answer.

I'm looping over 3 parameters for a somewhat long and complicated function and I noticed two things that I don't understand:

  1. The execution gets slower with each successive iteration, although the function only returns one struct (of which I only need one field) that I overwrite with each iteration.
  2. The profiler shows that the end statement for the innermost for takes a quite long time.

Consider the following example (I'm aware that this can easily be vectorized, but as far as I understand the function I call can't):

function stuff = doSomething( x, y, z )
    stuff.one = x+y+z;
    stuff.two = x-y-z;
end

and how I execute the function

n = 50;
i = 0;
currenttoc = 0;
output = zeros(n^3,4);
tic
for x = 1:n
    for y = 1:n
        for z = 1:n
            i = i + 1;
            output(i,1) = x;
            output(i,2) = y;
            output(i,3) = z;
            stuff = doSomething(x,y,z);
            output(i,4) = stuff.one;
            if mod(i,1e4) == 0 % only for demonstration, not in final script
                currenttoc = toc - currenttoc;
                fprintf(1,'time for last 10000 iterations: %f \n',currenttoc)
            end
        end
    end
end

How can I speed this up? Why does every iteration take longer than the one before? I'm pretty sure this is horrible programming, sorry for that.

Upvotes: 3

Views: 930

Answers (3)

Rasman
Rasman

Reputation: 5359

So, the problem gets largely eliminated when I replace the if statement with:

if mod(i,1e4) == 0 % only for demonstration, not in final script
    fprintf(1,'time for last 10000 iterations: %f \n',toc); tic;
end

I think the operation on toc may be causing the problem

Upvotes: 1

jerad
jerad

Reputation: 2028

It's MUCH faster if doSomething returns multiple output variables rather than a struct

function [out1,out2] = doSomething( x, y, z )
    out1 = x+y+z;
    out2 = x-y-z;
end

The fact that it gets slower on each subsequent iteration is strange and i have no explanation for it but hopefully that gives you some speed up at least.

Upvotes: 1

Jonas
Jonas

Reputation: 74940

When I replace the call to doSomething with output(i,4)=toc;, and I plot diff(output(:,4)), I see that it's the call to fprintf that takes longer and longer every time, apparently.

Removing the if-clause returns to every iteration taking about the same amount of time.

Upvotes: 2

Related Questions