tic - toc behavior

9 views (last 30 days)
Lask
Lask on 11 Aug 2017
Answered: Cam Salzberger on 14 Sep 2017
Hi all,
I'm analyzing how "tic toc" functions work in MATLAB. In the following example I use the loop:
tic
while toc<0.05
toc
end
This code simply shows the different lap values until 0.05s. When I checked the toc values MATLAB showed in the command Window I realized the first "toc" was at aprox. 12 ms, while for the rest of "tocs", the difference between them was aprox. 0.01 ms.
So my doubt is: why the first iteration takes so much time, while the others are executed much faster?
Thanks in advance.
  8 Comments
KSSV
KSSV on 11 Aug 2017
YOu should check with this:
tic
t1 = 0 ;
count = 0 ;
t2 = zeros(1,[]) ;
while t1<0.05
count = count+1 ;
t1 = toc ;
t2(count) = t1 ;
end
Stephen23
Stephen23 on 11 Aug 2017
Edited: Stephen23 on 11 Aug 2017
@KSSV: your code expands t2 inside the loop. How will that help measure the timing accuarately?

Sign in to comment.

Answers (1)

Cam Salzberger
Cam Salzberger on 14 Sep 2017
As José was saying, there is more happening the first iteration through the loop than all subsequent iterations.
MATLAB uses just-in-time compilation (JIT), which means that it will only compile the code as it goes through it. So the first iteration through the loop, it's compiling the loop as well as running. Subsequent iterations don't have to do the first step, so they are generally faster. If you want to try to get consistent loops through each time, you could use two loops, and only keep the time readings for the inner loop on the second time through:
tic
t = zeros(100000,1);
for outerIdx = 1:2
k = 1;
while toc<0.05
t(k) = toc;
k = k+1;
end
end
t(t==0) = [];
dt = diff(t);
fprintf('%.8f\n', dt(1:20))
Additionally, the function definition can be cached. So if you modify code, run it twice and only count the second run. Or better yet, run it many times and take an average of all but the first run.
Even then, it depends on what else is happening on your system and in MATLAB, as that can affect the resources allocated to it.
There are also more accurate tools than tic and toc for timing functions. timeit is one, but the profiler is generally a more useful tool.
-Cam

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!