# Time Comparison and Tic Toc

17 views (last 30 days)
Matt on 2 Nov 2012
I am having a little trouble using the tic toc function. (For background, I wanted to visualize the difference in calculation times between vectorized equations and for-loops, make a function, called timecompare that takes in a function handle ,fh, and a vector, x, at which to evaluate my function.)
My function timecompare should evaluate my function handle in two ways: (1) using a for-loop to evaluate fh at each element of x, and (2) by simply inputting the whole vector into fh. The structure is function is:
two inputs:
1) A function handle, fh.
2) An array of values, x, at which to evaluate the function handle.
three outputs:
1) time1, the total time it takes to evaluate fh at each value of x using a for-loop.
2) time2, the total time it takes to evaluate fh at each value of x by inputting the whole array into your function.
3) flag, which has a value of 1 if time1 > time2, or a value of 2 if time2 > time1.
function [time1, time2] = timecompare(fh,x)
tic
for ii = 1:length(x)
feval(fh,x(ii))
end
time1 = toc;
tic
feval(fh,x)
end
plot(fh)
clearly I am doing something in my code and it’s probably because I am not too familiar with tic toc. How should I go about fixing my code?

Arthur on 2 Nov 2012
Edited: Arthur on 2 Nov 2012
With tic toc you measure the time elapsed between the 'tic' and 'toc' command. So for instance
tic
%you code here
elapsedTime = toc
I guess your code should be something like this:
function [time1, time2] = timecompare(fh,x)
tic
for ii = 1:length(x)
feval(fh,x(ii))
end
time1 = toc;
tic
feval(fh,x)
time2 = toc;
Arthur on 3 Nov 2012
Ah yes my answer didn't include the flag. I was hoping you could include that yourself. A simple if statement.