Main Content

Optimize Generated Code for Fixed-Point Data Operations

This example shows how the code generator optimizes fixed-point operations by replacing expensive division operations with highly efficient product operations. This optimization improves execution speed.

Example Model

In the model rtwdemo_fixptdiv, two fixed point signals connect to a Divide block. The Number of inputs parameter has the value /*.

model='rtwdemo_fixptdiv';
load_system(model)
set_param(model,'HideAutomaticNames','off','SimulationCommand','Update')
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,'GenCodeOnly','on');
slbuild(model);
### Starting build procedure for: rtwdemo_fixptdiv
### Successful completion of code generation for: rtwdemo_fixptdiv

Build Summary

Top model targets built:

Model             Action          Rebuild Reason                                    
====================================================================================
rtwdemo_fixptdiv  Code generated  Code generation information file does not exist.  

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

View the generated code. Here is a portion of rtwdemo_fixptdiv.c.

cfile = fullfile(cgDir,'rtwdemo_fixptdiv_ert_rtw','rtwdemo_fixptdiv.c');
rtwdemodbtype(cfile,'/* Model step','/* Model initialize', 1, 0);
/* Model step function */
void rtwdemo_fixptdiv_step(void)
{
  /* Outport: '<Root>/Out1' incorporates:
   *  Inport: '<Root>/In1'
   *  Product: '<Root>/Divide'
   */
  rtY.Out1 = (int16_T)(rtU.In1 >> 3);
}

The generated code contains a highly efficient right shift operation instead of an expensive division operation. The generated code also contains the precomputed value for the constant input to the Product block.

Note that the resulting operation also includes the adjustment in signal scaling from 2^-3 to 2^-5.

Close the model and code generation report.

bdclose(model)
rtwdemoclean;
cd(currentDir)

Related Topics