Remove Code for Blocks That Have No Effect on Computational Results

This example shows how the code generator optimizes generated code by removing code that has no effect on computational results. This optimization:

  • Increases execution speed.

  • Reduces ROM consumption.

Example

In the model rtwdemo_blockreduction, a Gain block of value 1.0 is in between Inport and Outport blocks.

model = 'rtwdemo_blockreduction';
open_system(model);

Generate Code

Create a temporary folder for the build and inspection process.

currentDir=pwd;
[~,cgDir]=rtwdemodir();

Build the model.

set_param(model,'BlockReduction','off');
rtwbuild(model)
### Starting build procedure for: rtwdemo_blockreduction
### Successful completion of build procedure for: rtwdemo_blockreduction

Here is the code from rtwdemo_blockreduction.c.

cfile = fullfile(cgDir,'rtwdemo_blockreduction_ert_rtw','rtwdemo_blockreduction.c');
rtwdemodbtype(cfile, '/* Model step function */',...
    '/* Model initialize function */', 1, 0);
/* Model step function */
void rtwdemo_blockreduction_step(void)
{
  /* Outport: '<Root>/Out1' incorporates:
   *  Gain: '<Root>/Gain'
   *  Inport: '<Root>/In1'
   */
  rtwdemo_blockreduction_Y.Out1 = 1.0 * rtwdemo_blockreduction_U.In1;
}

Enable Optimization

  1. Open the Configuration Parameters dialog box.

  2. Select Block reduction. This optimization is on by default.

Alternately, use the command-line API to enable the optimization.

set_param(model,'BlockReduction','on');

Generate Code with Optimization

rtwbuild(model)
### Starting build procedure for: rtwdemo_blockreduction
### Successful completion of build procedure for: rtwdemo_blockreduction

Here is the optimized code from rtwdemo_blockreduction.c.

cfile = fullfile(cgDir,'rtwdemo_blockreduction_ert_rtw','rtwdemo_blockreduction.c');
rtwdemodbtype(cfile, '/* Model step function */',...
    '/* Model initialize function */', 1, 0);
/* Model step function */
void rtwdemo_blockreduction_step(void)
{
  /* Outport: '<Root>/Out1' incorporates:
   *  Inport: '<Root>/In1'
   */
  rtwdemo_blockreduction_Y.Out1 = rtwdemo_blockreduction_U.In1;
}

Because multiplying the input signal by a value of 1.0 does not impact computational results, the code generator excludes the Gain block from the generated code. Close the model and clean up.

bdclose(model)
rtwdemoclean;
cd(currentDir)

See Also

Related Topics