Measure the Performance of Your Code - MATLAB & Simulink (original) (raw)

Overview of Performance Timing Functions

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 Your Code to Improve Performance.

Time Functions

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(x,y); % handle to function timeit(f)

Time Portions of Code

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. Invokingtic 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.

The cputime Function vs. tic/toc and timeit

It is recommended that you use timeit ortic and toc to measure the performance of your code. These functions return wall-clock time. Unliketic 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 ortic/toc return, and could be misleading. For example:

Tips for Measuring Performance

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

See Also

timeit | tic | toc | profile