I have a program running a loop I want to have two time counters, one for the loop, that will tell me how log did one iteration of the loop took, and one for the entire program. To the best of my knowledge tic
and toc
will work only once.
Take Measurements Using Multiple tic CallsUse a pair of tic and toc calls to report the total time required for element-by-element matrix multiplication; use another pair to report the total runtime of your program. The variable tMul includes the total time spent on multiplication.
To measure the time required to run a function, use the timeit function. The timeit function calls the specified function multiple times, and returns the median of the measurements. It takes a handle to the function to be measured and returns the typical execution time, in seconds.
The tic function records the current time, and the toc function uses the recorded value to calculate the elapsed time. example. timerVal = tic stores the current time in timerVal so that you can pass it explicitly to the toc function.
You're only familiar with this tic toc syntax:
tic; someCode; elapsed = toc;
But there is another syntax:
start = tic; someCode; elapsed = toc(start);
The second syntax makes the same time measurement, but allows you the option of running more than one stopwatch timer concurrently. You assign the output of tic to a variable tStart and then use that same variable when calling toc. MATLAB measures the time elapsed between the tic and its related toc command and displays the time elapsed in seconds. This syntax enables you to time multiple concurrent operations, including the timing of nested operations (matlab documentation of tic toc).
Here's how to use it in your case. Let's say that this is your code:
for i = 1:M someCode; end
Insert the tic and toc like this:
startLoop = tic; for i = 1:N startIteration = tic; someCode; endIteration = toc(startIteration); end endLoop = toc(startLoop);
You can also use the above syntax to create a vector for which the ith element is the time measurement for the ith iteration. Like this:
startLoop = tic; for i = 1:N startIteration(i) = tic; someCode; endIteration(i) = toc(startIteration(i)); end endLoop = toc(startLoop);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With