Documentation Center

  • Trial Software
  • Product Updates

Analyzing Your Program's Performance

Overview of Performance Timing Functions

The MATLAB® Profiler, the stopwatch timer functions tic and toc and the timeit function enable you to get information on how your program is performing and help you identify areas that need improvement. The Profiler is useful for measuring relative execution time and identifying specific performance bottlenecks in code. The timeit function provides a robust measurement of the time required for function execution. Since the function provides a more vigorous estimate, use it instead of the stopwatch timer functions. Use tic and toc to estimate time for smaller portions of code that are not complete functions.

Time Functions

To measure the time required to run a function, use the timeit function. The timeit function takes a handle to the function to be measured and returns the typical execution time, in seconds. Suppose 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 = @() computeFunction(x,y); % handle to function
timeit(f)

Time Portions of Code

If you need to estimate how long a portion of your program takes to run or compare the speed of different implementations of portions of your program, you can use the stopwatch timer functions, tic and toc. Invoking tic starts the timer, and the next toc reads the elapsed time.

Use tic and toc as shown here:

tic
   -- The program section to time. --
toc

Keep in mind that tic and toc measure overall elapsed time. Make sure that no other applications are running in the background on your system that could affect the timing of your MATLAB programs.

Time Smaller Sections of Code

Shorter programs sometimes run too fast for tic and toc to provide useful data. In this case, try measuring the program running repeatedly in a loop, and then average to find the time for a single run.

tic
   for k = 1:100
      -- The program section to time. --
   end
toc

The cputime Function vs. tic/toc and timeit

Although you can measure performance using the cputime function, the timeit or tic and toc functions are better for this purpose. Generally for CPU-intensive calculations run on Microsoft® Windows® machines, the elapsed time using cputime and using tic and toc are close in value, ignoring any first time costs. There are cases, however, that show a significant difference between these methods. For example, in the case of a Pentium 4 with hyperthreading running Windows, there can be a significant difference between the values returned by cputime versus tic and toc.

Like tic and toc, timeit provides more reliable results than cputime. However, the timeit function additionally takes first-time costs into account.

See Also

| |

Related Examples

Was this topic helpful?