The timeit
function and
the stopwatch timer functions, tic
and toc
, enable you to time how long your
code takes to run. Use the timeit
function
for a rigorous measurement of function execution time. Use tic
and toc
to
estimate time for smaller portions of code that are not complete functions.
For additional details about the performance of your code, such as function call information and execution time of individual lines of code, use the MATLAB® Profiler. For more information, see Profile to Improve Performance.
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. Suppose that you
have defined a function, computeFunction
, that
takes two inputs, x
and y
, that
are defined in your workspace. You can compute the time to execute
the function using timeit
.
f = @() myComputeFunction; % handle to function timeit(f)
To estimate how long a portion of your program takes to run
or to compare the speed of different implementations of portions of
your program, use the stopwatch timer functions, tic
and toc
.
Invoking tic
starts the timer, and the next toc
reads
the elapsed time.
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.
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.
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
.