AMD x86 manual Avoid Unnecessary Integer Division, Example 1 Avoid

Models: x86

1 256
Download 256 pages 58.62 Kb
Page 47
Image 47

22007E/0 — November 1999

AMD Athlon™ Processor x86 Code Optimization

Avoid Unnecessary Integer Division

Integer division is the slowest of all integer arithmetic operations and should be avoided wherever possible. One possibility for reducing the number of integer divisions is multiple divisions, in which division can be replaced with multiplication as shown in the following examples. This replacement is possible only if no overflow occurs during the computation of the product. This can be determined by considering the possible ranges of the divisors.

Example 1 (Avoid):

int i,j,k,m;

m = i / j / k;

Example 2 (Preferred):

int i,j,k,l;

m = i / (j * k);

Copy Frequently De-referenced Pointer Arguments to Local Variables

Avoid frequently de-referencing pointer arguments inside a function. Since the compiler has no knowledge of whether aliasing exists between the pointers, such de-referencing can not be optimized away by the compiler. This prevents data from being kept in registers and significantly increases memory traffic.

Note that many compilers have an “assume no aliasing” optimization switch. This allows the compiler to assume that two different pointers always have disjoint contents and does not require copying of pointer arguments to local variables.

Otherwise, copy the data pointed to by the pointer arguments to local variables at the start of the function and if necessary copy them back at the end of the function.

Avoid Unnecessary Integer Division

31

Page 47
Image 47
AMD x86 manual Avoid Unnecessary Integer Division, Example 1 Avoid