Main Content

Optimize Global Variable Usage

To tune your application and choose tradeoffs for execution speed and memory usage, you can choose a global variable reference optimization for the generated code.

On the Configuration Parameters dialog box, in the Optimize global data access drop-down list, three parameter options control global variable usage optimizations.

  • None. Use default optimizations. This choice works well for most models. The code generator balances the use of local and global variables. It generates code which balances RAM and ROM consumption and execution speed.

  • Use global to hold temporary results. Reusing global variables improves code efficiency and readability. This optimization reuses global variables, which results in the code generator defining fewer variables. It reduces RAM and ROM consumption and data copies.

  • Minimize global data access. Using local variables to cache global data reduces ROM consumption by reducing code size. This optimization improves execution speed because the code uses fewer instructions for local variable references than for global variable references.

    Minimizing the use of global variables by using local variables interacts with stack usage control. For example, stack size can determine the number of local and global variables that the code generator can allocate in the generated code. For more information, see Customize Stack Space Allocation.

Use Global to Hold Temporary Results

The code generator uses global and local variables when you select None versus when you select Use global to hold temporary results.

Example Model

In the model UseGlobalsForTemporaryResults, an Assignment block assigns values coming from the Inport and Constant blocks to an output signal. The output signal feeds into a Gain block.

UseGlobalsForTemporaryResultsModel.png

model = 'UseGlobalsForTemporaryResults';
load_system('UseGlobalsForTemporaryResults')

Generate Code Without Optimization

  1. In the Configuration Parameters dialog box, verify that the Signal storage reuse parameter is selected.

  2. In the Configuration Parameters dialog box, for the Optimize global data access parameter, select None or enter the following command in the MATLAB® Command Window:

set_param('UseGlobalsForTemporaryResults','GlobalVariableUsage','None');

Build the model.

slbuild(model);
### Starting build procedure for: UseGlobalsForTemporaryResults
### Successful completion of build procedure for: UseGlobalsForTemporaryResults

Build Summary

Top model targets built:

Model                          Action                        Rebuild Reason                                    
===============================================================================================================
UseGlobalsForTemporaryResults  Code generated and compiled.  Code generation information file does not exist.  

1 of 1 models built (0 models already up to date)
Build duration: 0h 0m 14.501s

View the generated code without the optimization. Here is a portion of UseGlobalsForTemporaryResults.c.

cfile = fullfile(pwd,'UseGlobalsForTemporaryResults_ert_rtw',...
    'UseGlobalsForTemporaryResults.c');
coder.example.extractLines(cfile,'/* Model step','/* Model initialize',1, 0);
/* Model step function */
void UseGlobalsForTemporaryResults_step(void)
{
  real_T rtb_Assignment[5];
  int32_T i;

  /* SignalConversion generated from: '<Root>/Assignment' incorporates:
   *  Constant: '<Root>/Constant'
   */
  for (i = 0; i < 5; i++) {
    rtb_Assignment[i] = rtCP_Constant_Value[i];
  }

  /* End of SignalConversion generated from: '<Root>/Assignment' */

  /* Assignment: '<Root>/Assignment' incorporates:
   *  Inport: '<Root>/In1'
   */
  rtb_Assignment[1] = rtU.In1;

  /* Outport: '<Root>/Out1' incorporates:
   *  Gain: '<Root>/Gain'
   */
  for (i = 0; i < 5; i++) {
    rtY.Out1[i] = 2.0 * rtb_Assignment[i];
  }

  /* End of Outport: '<Root>/Out1' */
}

The code assigns values to the local vector rtb_Assignment. The last statement copies the values in the local vector rtb_Assignment to the global vector rtY.Out1. Fewer global variable references result in improved execution speed. The code uses more instructions for global variable references than for local variable references.

In the Static Code Metrics Report, examine the Global Variables section.

  1. In the Code Generation Report window, select Static Code Metrics Report.

  2. Scroll down to the Global Variables section.

  3. Select the [+] sign before each variable to expand it.

The total number of reads and writes for global variables is 2.

Generate Code with Optimization

In the Configuration Parameters dialog box, for the Optimize global data access parameter, select Use global to hold temporary results, or enter the following command in the MATLAB Command Window:

set_param('UseGlobalsForTemporaryResults',...
    'GlobalVariableUsage','Use global to hold temporary results');

Build the model.

slbuild(model);
### Starting build procedure for: UseGlobalsForTemporaryResults
### Successful completion of build procedure for: UseGlobalsForTemporaryResults

Build Summary

Top model targets built:

Model                          Action                        Rebuild Reason                   
==============================================================================================
UseGlobalsForTemporaryResults  Code generated and compiled.  Generated code was out of date.  

1 of 1 models built (0 models already up to date)
Build duration: 0h 0m 13.228s

View the generated code with the optimization. Here is a portion of UseGlobalsForTemporaryResults.c.

cfile = fullfile(pwd,'UseGlobalsForTemporaryResults_ert_rtw',...
    'UseGlobalsForTemporaryResults.c');
coder.example.extractLines(cfile,'/* Model step','/* Model initialize',1, 0);
/* Model step function */
void UseGlobalsForTemporaryResults_step(void)
{
  int32_T i;

  /* SignalConversion generated from: '<Root>/Assignment' incorporates:
   *  Assignment: '<Root>/Assignment'
   *  Constant: '<Root>/Constant'
   */
  for (i = 0; i < 5; i++) {
    rtY.Out1[i] = rtCP_Constant_Value[i];
  }

  /* End of SignalConversion generated from: '<Root>/Assignment' */

  /* Assignment: '<Root>/Assignment' incorporates:
   *  Inport: '<Root>/In1'
   */
  rtY.Out1[1] = rtU.In1;

  /* Outport: '<Root>/Out1' incorporates:
   *  Assignment: '<Root>/Assignment'
   *  Gain: '<Root>/Gain'
   */
  for (i = 0; i < 5; i++) {
    rtY.Out1[i] *= 2.0;
  }

  /* End of Outport: '<Root>/Out1' */
}

The code assigns values to the global vector rtY.Out1 without using a local variable. This assignment improves ROM and RAM consumption and reduces data copies. The code places the value in the destination variable for each assignment instead of copying the value at the end. In the Static Code Metrics Report, examine the Global Variables section.

As a result of using global variables to hold local results, the total number of reads and writes for global variables has increased from 2 to 5. This optimization reduces data copies by reusing global variables.

Close the code generation report.

Minimize Global Data Access

Generate optimized code that reads from and writes to global variables less frequently.

Example Model

In the model MinimizeGlobalDataAccess, five signals feed into a Multiport Switch block.

model = 'MinimizeGlobalDataAccess';
load_system('MinimizeGlobalDataAccess.slx')

MinimizeGlobalDataAccessModel.png

Generate Code Without Optimization

  1. In the Configuration Parameters dialog box, verify that the Signal storage reuse parameter is selected.

  2. In the Configuration Parameters dialog box, for the Optimize global data access parameter, select None or enter the following command in the MATLAB® Command Window:

set_param('MinimizeGlobalDataAccess','GlobalVariableUsage','None');

Build the model.

slbuild(model);
### Starting build procedure for: MinimizeGlobalDataAccess
### Successful completion of build procedure for: MinimizeGlobalDataAccess

Build Summary

Top model targets built:

Model                     Action                        Rebuild Reason                                    
==========================================================================================================
MinimizeGlobalDataAccess  Code generated and compiled.  Code generation information file does not exist.  

1 of 1 models built (0 models already up to date)
Build duration: 0h 0m 12.267s

View the generated code without the optimization. Here is a portion of MinimizeGlobalDataAccess.c.

cfile = fullfile(pwd,'MinimizeGlobalDataAccess_ert_rtw',...
    'MinimizeGlobalDataAccess.c');
coder.example.extractLines(cfile,'/* Model step','/* Model initialize',1, 0);
/* Model step function */
void MinimizeGlobalDataAccess_step(void)
{
  /* MultiPortSwitch: '<Root>/Multiport Switch' incorporates:
   *  Inport: '<Root>/In1'
   */
  switch ((int32_T)rtU.In1) {
   case 1:
    /* Outport: '<Root>/Out1' incorporates:
     *  Constant: '<Root>/Constant'
     */
    rtY.Out1 = 1.0;
    break;

   case 2:
    /* Outport: '<Root>/Out1' incorporates:
     *  Constant: '<Root>/Constant1'
     */
    rtY.Out1 = 2.0;
    break;

   case 3:
    /* Outport: '<Root>/Out1' incorporates:
     *  Constant: '<Root>/Constant2'
     */
    rtY.Out1 = 3.0;
    break;

   default:
    /* Outport: '<Root>/Out1' incorporates:
     *  Constant: '<Root>/Constant3'
     */
    rtY.Out1 = 4.0;
    break;
  }

  /* End of MultiPortSwitch: '<Root>/Multiport Switch' */
}

In the Static Code Metrics Report, examine the Global Variables section.

  1. In the Code Generation Report window, select Static Code Metrics Report.

  2. Scroll down to the Global Variables section.

  3. Select the [+] sign before each variable to expand it.

The total number of reads and writes for global variables is 5.

Enable Optimization and Generate Code

In the Configuration Parameters dialog box, for the Optimize global data access parameter, select Minimize global data access or enter the following command in the MATLAB Command Window:

set_param('MinimizeGlobalDataAccess',...
    'GlobalVariableUsage','Minimize global data access');

Build the model.

slbuild(model);
### Starting build procedure for: MinimizeGlobalDataAccess
### Successful completion of build procedure for: MinimizeGlobalDataAccess

Build Summary

Top model targets built:

Model                     Action                        Rebuild Reason                   
=========================================================================================
MinimizeGlobalDataAccess  Code generated and compiled.  Generated code was out of date.  

1 of 1 models built (0 models already up to date)
Build duration: 0h 0m 11.708s

View the generated code with the optimization. Here is a portion of MinimizeGlobalDataAccess.c.

cfile = fullfile(pwd,'MinimizeGlobalDataAccess_ert_rtw',...
    'MinimizeGlobalDataAccess.c');
coder.example.extractLines(cfile,'/* Model step','/* Model initialize',1, 0);
/* Model step function */
void MinimizeGlobalDataAccess_step(void)
{
  real_T tmp_Out1;

  /* MultiPortSwitch: '<Root>/Multiport Switch' incorporates:
   *  Inport: '<Root>/In1'
   */
  switch ((int32_T)rtU.In1) {
   case 1:
    /* Outport: '<Root>/Out1' incorporates:
     *  Constant: '<Root>/Constant'
     */
    tmp_Out1 = 1.0;
    break;

   case 2:
    /* Outport: '<Root>/Out1' incorporates:
     *  Constant: '<Root>/Constant1'
     */
    tmp_Out1 = 2.0;
    break;

   case 3:
    /* Outport: '<Root>/Out1' incorporates:
     *  Constant: '<Root>/Constant2'
     */
    tmp_Out1 = 3.0;
    break;

   default:
    /* Outport: '<Root>/Out1' incorporates:
     *  Constant: '<Root>/Constant3'
     */
    tmp_Out1 = 4.0;
    break;
  }

  /* End of MultiPortSwitch: '<Root>/Multiport Switch' */

  /* Outport: '<Root>/Out1' */
  rtY.Out1 = tmp_Out1;
}

In MinimizeGlobalDataAccess.c, the code assigns a constant value to the local variable tmp_Out1 in each case statement. The last statement in the code copies the value of tmp_Out1 to the global variable rtY.Out1. Fewer global variable references result in fewer instructions and improved execution speed.

In the Static Code Metrics Report, examine the Global Variables section. As a result of minimizing global data accesses, the total number of reads and writes for global variables has decreased from 5 to 2.

Close the code generation report.

See Also

Related Topics