Main Content

Performance and Memory

Profile code, improve performance, reduce memory requirements

Write your code to be simple and readable, especially for the first implementation. Code that is prematurely optimized can be unnecessarily complex without providing a significant gain in performance. Then, if speed is an issue, you can measure how long your code takes to run and profile your code to identify bottlenecks. If necessary, you can take steps to improve performance.

MATLAB® handles data storage for you automatically. However, if memory is an issue, you can identify memory requirements and apply techniques to use memory more efficiently.


expand all

ticStart stopwatch timer
tocRead elapsed time from stopwatch
cputimeCPU time used by MATLAB
timeitMeasure time required to run function
profileProfile execution time for functions
benchMATLAB benchmark
memoryMemory information
inmemNames of functions, MEX files, and classes in memory
packConsolidate workspace memory
memoizeAdd memoization semantics to function handle
MemoizedFunctionCall memoized function and cache results
clearAllMemoizedCachesClear caches for all MemoizedFunction objects


Measure and Profile Code

Measure the Performance of Your Code

Use the timeit function or the stopwatch timer functions, tic and toc, to time how long your code takes to run.

Profile Your Code to Improve Performance

Use the Profiler to measure the time it takes to run your code and identify which lines of code consume the most time or which lines do not run.

Determine Code Coverage Using the Profiler

To determine how much of a file MATLAB executes when you profile it, run the Coverage Report.

Improve Performance

Techniques to Improve Performance

To speed up the performance of your code, there are several techniques that you can consider.

Identify and Reduce Memory Requirements

How MATLAB Allocates Memory

Write more memory-efficient code by understanding how MATLAB allocates memory.

Strategies for Efficient Use of Memory

Reduce memory usage in your programs, use appropriate data storage, avoid fragmenting memory, and reclaim used memory.

Avoid Unnecessary Copies of Data

MATLAB can apply memory optimizations when passing function inputs by value.

Resolve “Out of Memory” Errors

Troubleshoot errors when MATLAB cannot allocate the requested memory.

Related Information