timeit function and
the stopwatch timer functions,
toc, enable you to time how long your
code takes to run. Use the
for a rigorous measurement of function execution time. Use
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
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,
takes two inputs,
are defined in your workspace. You can compute the time to execute
the function using
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 starts the timer, and the next
the elapsed time.
tic % The program section to time. toc
Sometimes programs run too fast for
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
measure the performance of your code. These functions return
wall-clock time. Unlike
timeit function calls your code
multiple times, and, therefore, considers first-time costs.
cputime function measures the
total CPU time and sums across all threads. This measurement
is different from the wall-clock time that
and could be misleading. For example:
The CPU time for the
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
clear all when measuring
performance. For more information, see the
Assign your output to a variable instead of letting
it default to