/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:
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.
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
我来评几句
登录后评论已发表评论数()