MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

tic
% The program section to time.
toc


Sometimes programs run too fast for tic and toc to provide useful data. If your code is
faster than 1/10 second, consider measuring it running in a loop, and then average to find
the time for a single run.


The cputime Function vs. tic/toc and timeit


It is recommended that you use timeit or tic and toc to measure the performance of
your code. These functions return wall-clock time. Unlike tic and toc,
the timeit function calls your code multiple times, and, therefore, considers first-time
costs.


The cputime function measures the total CPU time and sums across all threads. This
measurement is different from the wall-clock time that timeit or tic/toc return, and
could be misleading. For example:



  • The CPU time for the pause function is typically small, but the wall-clock time
    accounts for the actual time that MATLAB execution is paused. Therefore, the wall-
    clock time might be longer.

  • If your function uses four processing cores equally, the CPU time could be
    approximately four times higher than the wall-clock time.


Tips for Measuring Performance


Consider the following tips when you are measuring the performance of your code:



  • Time a significant enough portion of code. Ideally, the code you are timing should take
    more than 1/10 second to run.

  • Put the code you are trying to time into a function instead of timing it at the command
    line or inside a script.

  • Unless you are trying to measure first-time cost, run your code multiple times. Use the
    timeit function.

  • Avoid clear all when measuring performance. For more information, see the clear
    function.

  • Assign your output to a variable instead of letting it default to ans.


Measure Performance of Your Program
Free download pdf