Nested Timing
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.
- Category:
- Best Practice,
- Less Used Functionality
Comments
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.