MATLAB Answers

avarage running time problem

1 view (last 30 days)
fima v
fima v on 15 Apr 2020
Edited: Adam Danz on 15 Apr 2020
Hello, i want to calculte an avarage running time amongst all 100 iterations.
for some reason my avarage running time is astronomicly high
k = 3.6888e+11
where did i go wrong
for i=1:100
tic
1+1
2+2
toc
t(i)=tic-toc;
end
k=mean(t)

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 15 Apr 2020
Edited: Adam Danz on 15 Apr 2020
Here are three ways to use tic/toc to measure the timing of a loop. Each method has pros and cons.
Method 1: Least overhead
The tic() & toc() functions require processing time, albeit a very small amount. Storing the results of toc() also requires processing time. This method contains the least overhead but you don't get the single-iteration times.
start = tic();
for i=1:100
1+1;
2+2;
end
k= toc(start)/100;
Method 2: Single iterations times
This method gives you the single-iteration times but the processing time is added by tic/toc and storing the toc output.
t = nan(1, 100);
for i=1:100
start = tic();
1+1;
2+2;
t(i)=toc(start);
end
k=mean(t)
Method 3: Computing single iteration times
This method removes tic() from the loop which doesn't reduce the overhead by much but it's worth sharing. The single-iteration times are computed outside of the loop.
t = nan(1, 101);
start = tic();
t(1) = toc(start);
for i=1:100
1+1;
2+2;
t(i+1)=toc(start);
end
k=mean(diff(t))
% Compare that to (t(end)-t(1))/100
Reasons your timing was off
  • tic() returns an integer (uint64) that has meaning only for the toc function. Example: t = tic(); t = 1943576784277
  • toc() returns the elapsed time since the previous tic() which is very quick in your loop so you're subracting a tiny amount from a large, meaningless integer.
  • The 1+1 and 2+2 lines display the result of each iteration in the command window since those lines are not supressed with a semicolon (;). That takes a lot of time.
  • The t variable was not pre-allocated so the length of t grows with each iteration. That also takes a lot of time.
Since the computations are so simple, you'll find a wide range of mean(t) if you run that script many times. Consider using the timeit function.

  3 Comments

fima v
fima v on 15 Apr 2020
Hello, i need to measure the time of each iteration.Why did you put the tic out side the loop?
Thanks
Adam Danz
Adam Danz on 15 Apr 2020
I've updated my answer to show several different way to think about how the tic/toc functions can be used to time a loop. Method #2 is probably what you're looking for.
fima v
fima v on 15 Apr 2020
Thank you very much

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!