25112 Rev. 3.06 September 2005

Software Optimization Guide for AMD64 Processors

2.20Replacing Integer Division with Multiplication

Optimization

Replace integer division with multiplication when there are multiple divisions in an expression. (This is possible only if no overflow will occur during the computation of the product. The possibility of an overflow can be determined by considering the possible ranges of the divisors.)

Application

This optimization applies to:

32-bit software

64-bit software

Rationale

Integer division is the slowest of all integer arithmetic operations.

Examples

Avoid code that uses two integer divisions:

int i, j, k, m;

m = i / j / k;

Instead, replace one of the integer divisions with the appropriate multiplication:

m = i / (j * k);

Chapter 2

C and C++ Source-Level Optimizations

43

Page 59
Image 59
AMD 250 manual Replacing Integer Division with Multiplication, Examples