Why is my for loop getting faster and faster?

9 views (last 30 days)
So i have an m dimensional square matrix, and i loop over the elements a lot and update the elements with an equation as i go. Weirdest thing is that at the start, the iterations are slow, but get faster exponentially until they reach a limit of "maximum speed". I used tic toc to show this in a graph.
the horizontal axis represents the "i-th" iteration and the vertical axis is the speed of that iteration. I should note that the matrix elements are complex numbers, and they do not generally converge to some value. I'm sure my results are correct because i succesfully reproduced results of a published paper from 2005.
I found it amazing that the loop is getting faster, and I was wondering why that is happening. Also what sets the fastest time?
EDIT:
I did not post the loop code because i didn't think there was anything special about it. Here it is!
for j=2:length(t)
s=0;
tic
for jx=2:m-1
for jy=2:m-1
phi(3,jx,jy)=lel1(1,jx,jy)-(1i)*(2*h)*(eps(jx,jy)*lel2(1,jx,jy)+lel2(1,jx-1,jy)+lel2(1,jx+1,jy)+lel2(1,jx,jy-1)+lel2(1,jx,jy+1));
s=s+((jx-m/2)^2+(jy-m/2)^2)*abs(phi(3,jx,jy))^2;
end
end
timing(j-1) = toc;
r(j)=s;
lel1=lel2;
lel2=phi(3,:,:);
end
t is just an array for time (0:0.01:10). phi is a (3,m,m) array of complex numbers, and r is an array of length(t).
I can't have a bug because i reproduced the results in a published paper! and also the results make sense physically.
  1 Comment
Guillaume
Guillaume on 4 Dec 2019
Hard to tell without seeing your loop code.
If you were expecting the loop time to be constant then most likely you've got a bug!

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 4 Dec 2019
This doesn't strike me as a bug. I suspect this is due to the execution engine introduced in release R2015b (which uses just-in-time compilation) optimizing the body of the loop more effectively as it performs more and more iterations.
From this page on the MathWorks website: "The performance benefit of JIT compilation is greatest when MATLAB code is executed additional times and can re-use the compiled code. This happens in common cases such as for-loops or when applications are run additional times in a MATLAB session with at least some of the application’s MATLAB files remaining unmodified between subsequent runs."

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!