1806 - Simulink Performance & Memory Management Guide
This document is intended to help you understand and prevent 'Out of Memory' errors in Simulink and improve overall performance of your model. This technical guide helps you understand how Simulink uses memory, how to analyze where it is using its memory, and how to find areas that can be improved via modeling styles, settings, etc.
Contents
- Why do I get 'Out of Memory' Errors in Simulink?
- How do I Avoid Out of Memory Errors in Simulink?
- Why is my Simulink Model Running Slowly?
- How can I manage memory usage to allow code generation with very large models in Real-Time Workshop?
Section 1: Why do I get 'Out of Memory' Errors in Simulink?
You can run into performance issues with Simulink if the dynamic system modeled is mathematically difficult, if it is modeled inefficiently, or if you encounter memory issues. You may begin to run into memory issues with Simulink for numerous reasons, including a model becoming very large. Simulink has two main stages that affect when memory can be used:
- When a model is loading
- When a diagram is being updated
The main distinction between these two stages of a Simulink model is the first stage does not require the model to be ready to simulate, the second stage does.
Memory Used in Loading Simulink Models
When loading Simulink models, the main two areas that can use memory are:
- Data loaded by the model (and probably referenced, for example, workspace variables, table data, etc.).
- The blocks themselves (number of blocks, types of blocks, etc.).
As of R13SP1, Simulink has incremental loading of Simulink models. This means that if you load a root model that references libraries or Stateflow charts, those elements are not loaded into memory until a user navigates to them, or the model enters the diagram-updating stage mentioned in the introduction. You can see the breakdown of all blocks in a Simulink model (without the need of an update diagram) by using the sldiagnostics command with one of the available options. At the MATLAB command prompt, execute:
sldiagnostics(modelname,'countblocks')
Memory Used when Updating Diagrams
A Simulink model executes in stages. The two main stages are initialization and simulation.
- Initialization: In this phase, Simulink incorporates library blocks into the model; evaluates block parameters; propagates widths, data types, and sample times; determines block execution order; and allocates memory.
This initialization stage is represented during the diagram-updating action. It can be initiated by users via the option on the Edit menu of Simulink models. There are also various actions that initiate the diagram-updating stage implicitly. Simulating the model (via the Play button or sim command for instance) or generating code for the model are two examples.
There are two options to see diagnostics relating to the time taken and memory used during the diagram-updating stage.
Use an Additional Option to the Command sldiagnostics
- Start MATLAB with the '-check_malloc' option. Refer to the documentation on how this can be done on Windows or UNIX platforms.
- At the MATLAB command prompt, execute
sldiagnostics(modelname,'compilestats')
Use the Commands set_param and get_param
- At the MATLAB command prompt, execute:
set_param(bdroot,'DisplayCompileStats','on');
- Update the Simulink diagram using Ctrl+D.
- At the MATLAB command prompt, execute
stats = get_param(bdroot,'CompileStatistics')
The diagram-updating stage takes time because Simulink is performing all the actions noted in the initialization step.
- Simulation: This is the second major cause of Out of Memory errors and the second stage of a Simulink model execution. Data logging is only one reason why this can occur during a simulation.
Monitoring Memory Usage
The best way to see memory allocation is to open up the Task Manager and select the Processes tab. Under the View menu, make sure the following are selected:
- CPU Usage
- Memory Usage
- Memory Usage Delta
- Peak Memory Usage
- Virtual Memory Size
During the loading and update diagram stages, note if the Virtual Memory Size begins to build above the physical memory limit (i.e., physical memory has been exhausted). This means that disk swapping has begun and speed will dramatically decrease. It is also worth noting through these stages what the total Virtual Memory Size climbs to.
Note: MATLAB is just like any other application on your operating system. It will ask for memory throughout its operations and release it when done. This can lead to fragmentation of the available memory. This is described in detail in the How Do I Defragment the MATLAB Workspace Memory? section of the 1106 - Memory Management Guide.
You can check to see what are the top 10 segments of contiguous memory on that machine. It varies among different machines, operating systems, and product releases. It can be obtained using the following MATLAB command:
system_dependent('memstats')
There is a fundamental limitation of 32-bit operating systems that limits maximum contiguous block of memory to 2 GB. The total Windows memory for a single user application can be extended to 3 GB using the /3GB switch in Windows XP, but this is done by adding a separate noncontiguous 1 GB of memory. Hence if you are using Windows XP with the /3GB switch, you will never see the largest block larger of memory exceed 2 GB.
Section 2: How Do I Avoid Out of Memory Errors in Simulink?
The following guidelines are intended to help Simulink users maximize performance and minimize 'Out of Memory' errors.
There are two fundamental changes to memory in MATLAB 7.0 (R14) and above that you should review for better memory performance with Simulink models.
Optional Compact Memory Manager Inside MATLAB
This is the first of two fundamental changes to memory available as of MATLAB 7.0 (R14). The use of an optional compact memory manager removes alot of debugging overhead that isn't really necessary in most situations. You activate it by running a command-line flag or by setting a DOS environment variable at the Windows command (DOS) prompt so that when MATLAB runs, it sees that it should use a particular memory manager instead of the default memory manager.
-
Flag method:
D:\> D:\Applications\matlabr14fcs\bin\win32\MATLAB.exe -memmgr=compact
The flag method can be used in a shortcut by editing the shortcut's properties. Refer to the documentation on how this can be done on Windows or UNIX platforms.
-
Variable method:
D:\> set MATLAB_MEM_MGR=compact
D:\> D:\Applications\matlabr14fcs\bin\win32\MATLAB.exe
Support for Large Address Space on Windows 2000 and Windows XP
The 2.5 GB support on Windows 2000 (3 GB on Windows XP) has to be activated in Windows. Then MATLAB will recognize it and use the additional available memory.
Loading Referenced Simulink Data
When loading referenced data, use MAT-files within the model callbacks as opposed to M-files as much as possible. Loading data from MAT-files will store your data in a contiguous memory block, allowing for faster processing when compared to parsing through M-code to populate fixed variables. M-code can create temporary variables that might fragment available memory. Consider using MAT-files to store data as much as possible.
Note: As of R14, Simulink now has the concept of model workspaces. MAT-files can be located here with data that is referenced in particular to the models themselves. This feature solely adds a degree of freedom as to where to house data referenced by a model. It can be held via an M-file or MAT-file. MAT-files are preferred due to the previously stated issue.
Reduce the Number of Simulink Blocks
Reducing the number of blocks can reduce your memory requirements. There are some modeling styles that can lead to inefficiencies. Look for places in your model where you can reduce the block count such as heavily weighted areas to accomplish simple procedures. Here are some examples:
- Can you vectorize operations?
The following articles discuss techniques to improving your overall model efficiency.
Applied Simulink Modeling Techniques for Varying Signal Widths (Part I)
http://www.mathworks.com/company/newsletters/digest/may03/modeling.htmlApplied Simulink Modeling Techniques for Varying Signal Widths (Part II)
http://www.mathworks.com/company/newsletters/digest/july03/modtech.html
- Are your masked blocks simply a standard Simulink block within a subsystem?
This is usually done when customers only want to expose a subset of the standard block mask dialogs. It is best to simply mask the block directly. At a minimum, this eliminates two out of three blocks for each instance.
Model Componentization through Model Reference
Model componentization through model reference (as of R14) is one way that can drastically reduce the memory required to update a diagram for large models. Partitioning a large model is most efficient when done as close to the root level as possible. Model reference elements should be aligned with the way people work with various parts of the diagram. This will also reduce the block count, and should be employed when a subsystem from a library is employed many times.
Minimizing the Amount of Data Logged
You can save on memory as well as on performance by minimizing the amount of data that is logged. There are various good tools to quickly configure what is logged within a Simulink Model:
-
Simulink Model Explorer
The Model Explorer allows you quick access to your model signals and available logging options.
-
Data Import/Export Pane (from the Configuration Parameters UI)
You can decimate the data logged in the Save Options within the Data Import/Export Pane.
- Custom scripts such as these from MATLAB Central:
Avoiding Memory Allocation Errors
The following solution contains some common ways to avoid memory allocation errors in Simulink: http://www.mathworks.com/support/solutions/data/1-19HOC.html
Section 3: Why is my Simulink Model Running Slowly?
The first thing you must figure out is where and why the Simulink simulation is running slow. Many things can affect Simulink Performance:
- Modeling style
- Dynamic system modeled
- Tool inefficiencies
- Combination of the above
Here are a few areas that can be the culprit based on our experiences and practical ways to counter them:
- Update diagram: See the previous section on Memory Used when Updating Diagrams. In addition to memory used, the diagnostics examined in Section 1 also show the elapsed time during the update-diagram stage.
-
Overall simulation execution: This can be caused by:
- Small time steps.
- Iterative loop. This can severely degrade the simulation speed to the point that the model appears hung (suspended) at a certain time step (variable step solver).
There are two tools to help identify where/why your simulation is executing slowly, the Simulink Accelerator (which includes the Profiler) and the Simulink Debugger.
Simulink Accelerator
The Simulink Accelerator accelerates the simulation of Simulink models by creating and compiling C code that takes the place of the interpretive code that Simulink uses during Normal mode minimizing the time needed to simulate Simulink models. If after analyzing where your model is using its memory and you have improved your modeling styles and settings, the Simulink Accelerator will help in automatically speeding up your mathematically complex dynamic system. See the documentation for more information.
Simulink Profiler
The Simulink Accelerator comes with the Simulink Profiler, a tool that collects, analyzes, and displays simulation performance data. The Simulink Profiler collects performance data while simulating your model and generates a report, called a simulation profile, based on the data it has gathered. For more information refer to the documentation.
Using the Simulink Debugger to Extract Solver Diagnostics
Using the Simulink Debugger for analysis of simulation performance is an advanced maneuver. It gives access to a wealth of information pertaining to solver diagnostics. Using the debugger a user can identify many things that can cause slow execution such as:
- Certain states that are limiting the step size to grow when using a variable step solver.
- Certain zero-crossing events causing the solver to work extra hard in bounding the event.
- Solver resets may be occurring frequently due to inefficient modeling styles.
There are various techniques available through the Simulink Debugger command line interface that are especially useful. Below is a partial list from the complete list of Simulink Debugger commands:
- STRACE (set to level 4 for full information) - This option will let the you know about solver resets, zero crossings, failed step information, complete insight into internal workings through a major time step.
- BSHOW
- ZCLIST
- ZCBREAK (Available through Simulink Debugger GUI)
- RBREAK
- XBREAK - Identify state that limits solver step size
- SLIST (Available through Simulink Debugger GUI)
- SYSTEMS
- ATRACE and ASHOW - Algebraic Loop information
- STIMES
Information on Solver Performance
A summary of solver diagnostics can be recorded through a simulation using the following commands:
set_param(bdroot,'SolverProfileInfoName','My_Data')
set_param(bdroot,'SaveSolverProfileInfo','yes')
Once these are set, run the simulation. This returns a structure in the MATLAB variable (My_Data) entered of the following form:
stateInfo: [36x1 struct]
nSolverResets: 2108
nLUDecompositions: 0
nJacobianComputations: 0
Every continuous state, along with information relating to it, is within stateInfo. This structure also keeps track of solver resets, and other advanced metrics for certain stiff solvers. Exploring performance of various solvers is encouraged.
Section 4: How can I manage memory usage to allow code generation with very large models in Real-Time Workshop?
There are a number of measures you can take to increase the amount of memory available for code generation. One of the most important measures is to make sure you are running the most recent MATLAB release. We are constantly working to improve code generation performance for large models, so using a more recent release could provide an immediate benefit.
The following measures should also help improve the amount of memory available for code generation:
- Check out the Tech-Note article on MATLAB Memory Guide. It is a good resource for general memory usage considerations. In particular, consider using the /3GB boot switch with newer Windows versions:
-
Use the MATLAB_MEM_MGR environment variable to control the MATLAB memory manager. By default, MATLAB uses the 'cache'
memory manager. For reduced memory usage, use the following settings:
-
Windows Platforms: If you start MATLAB from a command prompt window or from a batch file (.bat), you can set
the environment variable before calling MATLAB with:
set MATLAB_MEM_MGR=fast
Alternatively, you can set the environment variable 'MATLAB_MEM_MGR' to the value of 'fast' from the system properties.
-
UNIX Platforms: You can set the environment variable 'MATLAB_MEM_MGR' to 'compact'. For example, with csh
(c shell), your .cshrc file would contain:
setenv MATLAB_MEM_MGR compact
-
Windows Platforms: If you start MATLAB from a command prompt window or from a batch file (.bat), you can set
the environment variable before calling MATLAB with:
- In Release 14, you can decompose large models into multiple models and reassemble them by using Model blocks (Model Reference). The use of Model blocks results in reduced memory usage through incremental code generation and simulation. See the Simulink documentation for information on Model Reference and current Model Reference feature limitations.
- If you do not need to use external mode, disable it in the Real-Time Workshop Interface pane of the Configuration Parameters by choosing None from the pull-down menu. For more information, refer to the Interface pane documentation.
-
Before generating code, restart MATLAB or use the following command sequence to reduce memory usage:
-
Close all Simulink models and clear the base workspace:
bdclose all;
clear all; - Then, reopen and build the model.
-
Close all Simulink models and clear the base workspace:
-
If you generate code using the right-click Build subsystem option, you can use the following procedure to increase
available memory:
- When the Build dialog appears, in the MATLAB Command Window, type the name of the subsystem as it appears in the dialog. This displays the temporary model that is used for the right-click build.
- Save the model.
- Cancel the original right-click build.
- Close the original model and reopen the saved subsystem model and build it separately.
-
Blocks that are links to libraries require additional memory to represent both the library and instances in the model. Consider breaking up library links in a model.
NOTE: This approach can be effective, but you should do this for the purpose of code generation only. You should not edit the model once links are broken overwriting the original model.
It is strongly recommended that you create a copy of the model first before breaking the library links by choosing Save As from the Simulink File menu. For more information, refer to the Simulink documentation on Breaking a Link to a Library Block and the potential effects such as the loss of automatic updated library version(s) of blocks propagating to your model.
- In terms of memory, it is always better to make a subsystem virtual (non-atomic). Atomic subsystems requires additional memory allocation.
- The longer term solution beyond more memory savings in MATLAB and Simulink is probably a 64-bit machine. For more information on 64-Bit architectures, refer to Section 1 Why Do I Get 'Out of Memory Errors in MATLAB?' of the Memory Management Guide.
Store