MATLAB: How to improve the runtime performance of the Simulink model’s externally-deployed generated code

Embedded Coder

How can I improve the runtime performance of the code that I am generating from my Simulink model and deploying to an external hardware device?

Best Answer

Here are some suggestions of ways you can improve the runtime performance of the code that is generated from your Simulink model:
1) Change the code generation optimization setting for the model. In "Configuration Parameters", navigate to "Code Generation", and change "Build Configuration" to "Faster Runs". This will compile the code at a higher optimization intended to reduce the runtime of the code.
2) Use the code replacement library (CRL) appropriate to your device (e.g. "ARM Cortex-M (CMSIS)" for ARM Cortex-M processors). In "Configuration Parameters", navigate to "Code Generation" > "Interface", and set "Code replacement library" to the appropriate setting. This will replace some of the functions (e.g. addition, multiplication, trigonometric functions) with hardware-optimized functions provided by the CRL wherever appropriate.
3) Use the most efficient data types. We recommend that you configure the model's signals to use the minimum required data type wherever possible. For example, if a variable can only take values between 0 and 130, a "uint16" data type would serve this purpose and be faster than a "double".
4) Increase the stack size. In "Configuration Parameters", navigate to "Code Generation" > "Optimization" > "Advanced parameters" (hidden under "..."), and set "Maximum stack size (bytes)" to 1024. This will create more local variables instead of global variables, but will use more resources.
5) Wherever possible, prefer to use built-in blocks over custom MATLAB Code. It is sometimes the case that built-in blocks will be able to generate more optimized code than MATLAB Function blocks, so try to use built-in blocks wherever possible.