MATLAB: Do TIC and TOC return incorrect results when a script containing TIC and TOC calls a function that contains another set of TIC and TOC calls

MATLABnested

TIC and TOC return incorrect results when a script containing TIC and TOC calls a function that contains another set of TIC and TOC calls.
This happens when I run the code below:
"test.m":
tic;
for i = 1:1000
a = myfunc(i,i+1)
end
toc
"myfunc.m":
function a = myfunc(x,y)
tic;
for i = 1:100000
a = x*i+y*(i+1);
end
toc
In this script file "test.m", I place a TIC and TOC around a FOR loop that calls the function "myfunc.m". Inside "myfunc.m", I also placed TIC and TOC around the code. Now, when "test.m" is executed, I received the elapsed time for running the function "myfunc.m" as well as receiving the last TOC, the elapsed time for the whole routine. However, (after I executed the code) it is obvious that this last elapsed time is less than the cumulative elapsed time from all the calls to "myfunc.m".

Best Answer

This enhancement has been incorporated in Release 2008b (R2008b). For previous product releases, read below for any possible workarounds:
The ability to nest TIC and TOC calls as documented is not available in MATLAB 7.6 (R2008a) and prior releases. To work around this issue, use the undocumented feature of using an input argument to TIC and TOC as shown from the modified code below:
"test.m":
t = tic;
for i = 1:3
a = myfunc(i,i+1);
end
s = toc(t);
display(['main TOC ', num2str(s)]) % Display elapsed time

"myfunc.m":
function a = myfunc(x,y)
t = tic;
for i = 1:5000
a = x*i+y*(i+1);
end
s = toc(t);
display(['myfunc TOC ', num2str(s)]) % Display elapsed time
Related Question