Main Content

Tips for Making Generated Code More Efficient

fimath Settings for Efficient Code

The default settings of the fimath object offer the smallest rounding error and prevent overflows. However, they can result in extra logic in generated code. These default settings are:

  • RoundingMethod: Nearest

  • OverflowAction: Saturate

  • ProductMode: FullPrecision

  • SumMode: FullPrecision

For leaner code, it is recommended that you match the fimath settings to the settings of your processor.

  • The KeepLSB setting for ProductMode and SumMode models the behavior of integer operations in the C language. KeepMSB for ProductMode models the behavior of many DSP devices.

  • Different rounding methods require different amounts of overhead code. Setting the RoundingMethod property to Floor, which is equivalent to two’s complement truncation, provides the most efficient rounding implementation for most operations. For the divide function, the most efficient RoundingMethod is Zero.

  • The standard method for handling overflows is to wrap using modulo arithmetic. Other overflow handling methods create costly logic. It is recommended that you set the OverflowAction property to Wrap when possible.

Replace Functions With More Efficient Fixed-Point Implementations

CORDIC

The CORDIC-based algorithms are among the most hardware friendly because they require only iterative shift-add operations. Replacing functions with one of the CORDIC implementations can make your generated code more efficient. For a list of the CORDIC functions, and examples of them being implemented, see CORDIC Algorithms.

Lookup tables

You can implement some functions more efficiently by using a lookup table approach. For an example, see Implement Fixed-Point Log2 Using Lookup Table.

Division

Division is often not supported by hardware. When possible, it is best to avoid division operations.

When the denominator is a power of two, you can rewrite the division as a bit shift operation.

x/8

can be rewritten as

bitsra(x,3)

Other times it is more efficient to implement division as a multiplication by a reciprocal.

x/5

can be rewritten as

x*0.2