Main Content

Multithreaded Simulation Using For Each Subsystem

This example shows how to speed up execution of a model on multiple cores using a For Each subsystem in Rapid Accelerator simulation mode.

Measure the Single-Threaded Simulation Time

In this model, a For Each subsystem accepts a numeric array input. Each element of the array serves as an upper bound in each iteration and feeds into a computationally-intensive algorithm represented by the MATLAB Function block inside the subsystem. The algorithm implemented in the MATLAB Function block computes the largest prime number within a given range using a brute force method, which is for illustrative purposes only.

modelName = 'slexForEachMultithreaded';

By default, the multithreaded simulation support for the For Each subsystem is enabled. To opt out of multithreaded simulation, issue a set_param command in the MATLAB® Command Window. In a single-threaded simulation, the computations in different iterations of the For Each subsystem are executed sequentially during each time step.

set_param(modelName, 'MultithreadedSim', 'off');

Since running in Rapid Accelerator mode creates files, first create a temporary directory and move to it.

originalDir = pwd;
tempDir = tempname;

Build the Rapid Accelerator target for the model. The progress of the code generation and build process is displayed in the MATLAB Command Window. To suppress this display, wrap the command inside evalc.


This build step is optional because Simulink® automatically generates the Rapid Accelerator simulation target the first time you simulate the model. In the example, this step serves to separate the overhead in generating the Rapid Accelerator target from the actual model execution time.

Once the Rapid Accelerator target is generated, simulate the model and measure the simulation time using tic and toc.

Elapsed time is 38.757731 seconds.

Use Multithreaded Simulation for Speedup on Multiple Cores

To explicitly opt in to multithreading support, issue a set_param command in the MATLAB Command Window. In a multithreaded simulation, the computations in different iterations of the For Each subsystem are assigned to multiple cores and executed in parallel for speedup.

set_param(modelName, 'MultithreadedSim', 'auto');

Build the Rapid Accelerator target again, since the model has been reconfigured.


Simulate the model again and measure the multithreaded simulation time. Notice that the model simulation runs over two times faster than the single-threaded simulation on a machine with four or more cores. Remember that operating system context-switching in multithreaded simulations always results in extra overhead.

Elapsed time is 21.396412 seconds.

Clean Up

Close the model and remove the generated files.

rmdir(tempDir, 's');
clear originalDir tempDir;

See Also