Main Content

Optimize Generated Code by Combining MultipleforConstructs

This example shows how the code generator combinesforloops. The generated code usesforconstructs to represent a variety of modeling patterns, such as a matrix signal or Iterator blocks. Using data dependency analysis, the code generator combinesforconstructs to reduce static code size and runtime branching.

The benefits of optimizingforloops are:

  • Reducing ROM and RAM consumption.

  • Increasing execution speed.

forLoop Modeling Patterns

Open the example modelForLoopConstruct. The Switch block and MATLAB Function block representforconstructs. In theIn1Block Parameters dialog box, thePort dimensionsparameter is set to10.

model ='ForLoopConstruct'; open_system(model);

Generate Code

The model does not contain data dependencies across theforloop iterations. Therefore, the code generator combinesforloops into one loop.

Build the model.

slbuild(model)
### Starting build procedure for: ForLoopConstruct ### Successful completion of build procedure for: ForLoopConstruct Build Summary Top model targets built: Model Action Rebuild Reason ================================================================================================== ForLoopConstruct 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 22.135s

视图中的优化代码ForLoopConstruct.c.

cfile = fullfile('ForLoopConstruct_grt_rtw','ForLoopConstruct.c'); rtwdemodbtype(cfile,'/* Model step','/* Model initialize', 1, 0);
/* Model step function */ void ForLoopConstruct_step(void) { real_T In1; int32_T k; /* MATLAB Function: '/Accum' */ /* MATLAB Function 'Accum': ':1' */ /* ':1:3' */ /* ':1:4' */ ForLoopConstruct_Y.Out1 = 0.0; /* ':1:5' */ for (k = 0; k < 10; k++) { /* Gain: '/G1' incorporates: * Inport: '/In1' */ In1 = ForLoopConstruct_U.In1[k]; /* Switch: '/Switch' incorporates: * Gain: '/G1' * Gain: '/G3' * Sum: '/Sum1' * Sum: '/Sum2' * UnitDelay: '/Delay' */ if (3.0 * In1 >= 0.0) { In1 -= ForLoopConstruct_DW.Delay_DSTATE[k]; } else { In1 = (ForLoopConstruct_DW.Delay_DSTATE[k] - In1) * 5.0; } ForLoopConstruct_DW.Delay_DSTATE[k] = In1; /* End of Switch: '/Switch' */ /* MATLAB Function: '/Accum' */ /* ':1:6' */ ForLoopConstruct_Y.Out1 += ((real_T)k + 1.0) + In1; } }

The generated code contains code for the singleforloop.

Close the model

bdclose(model) rtwdemoclean;

Related Topics