# avarage running time problem

5 views (last 30 days)
fima v on 15 Apr 2020
Edited: Adam Danz on 28 Jan 2021
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)

Adam Danz on 15 Apr 2020
Edited: Adam Danz on 28 Jan 2021
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 & resolution
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: Single iterations times, less overhead
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
• 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.
fima v on 15 Apr 2020
Thank you very much