We observed a strange behavior that the second toc in "tic;toc;toc;toc" sequence took longer than other tocs being called consequently. What's the reason? A testing function is attached below. See it for yourself and please let me know if you know the reason. Thank you in advance!
%%TICTOCTEST Test the tic-toc stopwatch timer
% Observe a strange behavior that the second toc in "tic;toc;toc;"
% sequence takes longer than other consequent tocs.
%
function tictoctest(k)%%Memory allocation effect
% to create a null matrix to allocate the memory space first.
% This is to avoid dynamic memory allocation effect in between tocs.
% Dynamic memory allocation delays the second toc even more.
% Comment out the following line and test it again
%tocs = zeros(k,6);
%%For loop
% to repeat "tic;toc;toc;toc;toc;toc;toc" k times and record the time
for i = 1:k tic; tocs(i,1) = toc; tocs(i,2) = toc; % the second toc!
tocs(i,3) = toc; tocs(i,4) = toc; tocs(i,5) = toc; tocs(i,6) = toc; pause(0.001); % this also affects the results.
end%%Post processing
% to calculate the differences between consequent tocs.
% This is to minimize the time for calculating differences in the for loop.
elapsed(:,1) = tocs(:,1);elapsed(:,2) = tocs(:,2) - tocs(:,1);elapsed(:,3) = tocs(:,3) - tocs(:,2);elapsed(:,4) = tocs(:,4) - tocs(:,3);elapsed(:,5) = tocs(:,5) - tocs(:,4);elapsed(:,6) = tocs(:,6) - tocs(:,5);%%Plot a boxplot
boxplot(elapsed)ylim([0 0.00003]) % limit y-axis to see the plot better
Best Answer