Main Content

减少中间的计算和存储Results at Block Outputs

Expression Folding

Expression foldingoptimizes code to minimize the computation of intermediate results at block outputs and the storage of such results in temporary buffers or variables. When expression folding is on, the code generator collapses (folds) block computations into a single expression, instead of generating separate code statements and storage declarations for each block in the model. Most Simulink blocks support expression folding.

Expression folding improves the efficiency of generated code, frequently achieving results that compare favorably to hand-optimized code. In many cases, entire groups of model computations fold into a single, highly optimized line of code.

You can use expression folding in your own inlined S-function blocks. For more information, seeS-Functions That Support Expression Folding.

Example Model

Generate Code

With expression folding off, in theexplfld.cfile, the code generator generates this code.

/* Model step function */ void exprfld_step(void) { /* Gain: '/Gain' incorporates: * Inport: '/In1' */ exprfld_B.S1 = exprfld_P.Gain_Gain * exprfld_U.i1; /* Gain: '/Gain1' incorporates: * Inport: '/In2' */ exprfld_B.S2 = exprfld_P.Gain1_Gain * exprfld_U.i2; /* Outport: '/Out1' incorporates: * Product: '/Product' */ exprfld_Y.Out1 = exprfld_B.S1 * exprfld_B.S2; }

There are separate code statements for both Gain blocks. Before final output, these code statements compute temporary results for the Gain blocks.

Enable Optimization

Expression folding is on by default. To see if expression folding is on for an existing model:

  1. Expression folding is available only when theConfiguration Parameters>标志al storage reuseparameter is selected because expression folding operates only on expressions involving local variables. Enable the标志al storage reuseparameter.

  2. When you select标志al storage reuse,Enable local block outputs,Reuse local block outputs, andEliminate superfluous local variables (expression folding)parameters are all on by default.

Generate Code with Optimization

With expression folding, the code generator generates a single-line output computation, as shown in theexpfld.cfile. The generated comments document the block parameters that appear in the expression.

/* Model step function */ void exprfld_step(void) { /* Outport: '/Out1' incorporates: * Gain: '/Gain' * Gain: '/Gain1' * Inport: '/In1' * Inport: '/In2' * Product: '/Product' */ exprfld_Y.Out1 = exprfld_P.Gain_Gain * exprfld_U.i1 * (exprfld_P.Gain1_Gain * exprfld_U.i2); }

For an example of expression folding in the context of a more complex model, clickrtwdemo_slexprfold, or at the command prompt, type:

rtwdemo_slexprfold

For more information, seeEnable and Reuse Local Block Outputs in Generated Code

See Also

|||

Related Topics