MATLAB: Tic toc in subfunctions

tic toc

I have the following code. I need to use tic toc to find out how much faster one loop runs versus the other. So far I have done several things. When I put tic after "function f = fact1(n);" and toc before "end" inside the for loop, and the same thing in the while loop, I get very tiny time numbers- 0.000006 seconds or something. And both of the times are the same. However, when I erase those commands in my editor window, and write the following in the command window instead: tic; my_factorial(5, 'for_loop'); toc; I get very different, and much larger numbers. However, I have also found that when I enter the above in the command window, and repeat the tic toc calculation several times, I get different values for elapsed time every time, even though the n and method remains the same. Sometimes I get a shorter time for my for loop vs. while, for the same n and method, and sometimes the situation is reversed. Why is that?
function f = my_factorial(n, method)
switch method
% To choose for loop method for computing factorial
case 'for_loop'
f = fact1(n);
% To choose while loop method for computing factorial
case 'while_loop';
f = fact2(n);
end
end
function f = fact1(n);
for loop
end
function f = fact2(n);
while loop
end

Best Answer

Note: timeit was introduced in R2013b. For earlier releases, you can find timeit in the file exchange.