# Why is my for loop getting faster and faster?

2 ビュー (過去 30 日間)
ashod khederlarian 2019 年 12 月 4 日
Answered: Steven Lord 2019 年 12 月 4 日
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 件のコメント

Guillaume 2019 年 12 月 4 日
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!

サインイン to comment.

### 採用された回答

Steven Lord 2019 年 12 月 4 日
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."

#### 0 件のコメント

サインイン to comment.