Did you know that you can use tic and toc to measure times of operations that may have other timed operations nested inside?
Contents
Example
Suppose I want to see how long some operations take, and the overall calculation as well. Let's see how long it takes to create some magic squares and how long it takes to find the rank for each one.
Nsizes = [10 20 50 100 200 500 1000]; N = numel(Nsizes); magTimes = zeros(1,N); rankTimes = zeros(1,N); ranks = zeros(1,N); timeTemp = tic; for k = 1:N mTemp = tic; m = magic(Nsizes(k)); magTimes(k) = toc(mTemp); rTemp = tic; ranks(k) = rank(m); rankTimes(k) = toc(rTemp); end allTimes = toc(timeTemp);
Compare Times
If I sum the times for creating the magic squares and computing their ranks, I should get the same time as the overall time calculation, right?
totTimes = sum(magTimes)+sum(rankTimes)
totTimes =
4.0211
allTimes
allTimes =
4.0344
The totals don't match! That's because there's other stuff going on in the loop, including overhead for managing the loop.
Timing Tips
To get relative time estimates, you can use the profiler, tic/toc, or Steve's timeit function on the file exchange. Though I am not doing so in this post, you generally should time functionality written in functions, especially if getting the best performance is your goal.
What are Your Timing Patterns?
Do you find yourself timing nested calculations? Do you have other strategies? Please post them here.
Get
the MATLAB code
Published with MATLAB® 7.7



We can now calculate the overhead of tic/toc using tic/toc :)
function tictoc t = tic; for i=1:1e5 t2 = tic; ignore=toc(t2); % suppress output end % convert to millisec overhead = (toc(t)/1e5)*1e3The overhead value I get (on my 1.8 GHz dual core Intel) is 0.0124 milliseconds. Not bad!
for long operations I prefer the output in a datestr format and not just raw seconds. This is mostly for jobs that take more than an hour. This is my timing pattern:
t0=now; for i=1:1000 % do some stuff fprintf('iter: %d time:%s\n',i,datestr(now-t0,13)); end