Rate This Document
Findability
Accuracy
Completeness
Readability

Multiplication and Division Optimization

Principles

The CPU spends different instruction cycles in processing different instructions. Each shift operation and addition and subtraction requires only one instruction cycle, multiplication requires three instruction cycles, and division requires 6 to 20 instruction cycles. You need to use an instruction with an instruction cycle as short as possible to implement a same function, so that the program running can be effectively accelerated.

Modification Method

  • Use shift operations to replace multiplication and division operations.

    Before:

    int a = 8;
    int b = 2;
    int c = a / b;
    int d = a * b;

    After:

    int a = 8;
    int c = a >> 1;
    int d = a << 1;
  • Use multiplication operations to replace division operations.

    Before:

    float a = x / 2.13;

    After:

    const float b = 1.0 / 2.13;
    float a = x * b;