Code Optimization-II
Code Optimization-II
After optimization:
[email protected] 05/07/2023 13
Loop Optimization - Loop Unrolling
● remove loop or reduce iterations of the loop
After optimization:
[email protected] 05/07/2023 14
Loop Optimization - Loop Jamming
● combining two or more loops in a single loop
After optimization:
Before optimization:
for(int i=0; i<5; i++)
for(int i=0; i<5; i++)
{
a = i + 5;
a = i + 5;
for(int i=0; i<5; i++)
b = i + 10;
b = i + 10;
}
[email protected] 05/07/2023 15
Loop Optimization - Loop Fusion
● Similar to Jamming but some parts of the expressions are also merged
Before optimization:
int acc = 0; After optimization:
for (int i = 0; i < n; ++i)
{ int acc = 0;
acc += a[i]; for (int i = 0; i < n; ++i)
a[i] = acc; {
} acc += a[i];
for (int i = 0; i < n; ++i) a[i] = acc;
{ b[i] += acc;
b[i] += a[i]; }
} [email protected] 05/07/2023 16
Loop Optimization - Elimination of induction variables
● A variable is called an Induction variable if its value in any loop gets changed
every time
After optimization:
Before optimization:
i=0
i=0
x=0
L1: i = i+1
L1: i = i+1
x = i*3
x = x+3
if x< 10 goto L2
if x< 10 goto L2
[email protected] 05/07/2023 21
Loop Optimization - Loop Interchange
● In nested loops, inner and outer loops are interchanged - improves locality of
reference
[email protected] 05/07/2023 22
Loop Optimization - Loop Invariant Removal
● Expression which has computation involved are avoided inside loop
Before optimization:
After optimization:
L1: t = 0
L1: t = 0
t=a+b
L2: i = i + 1
L2: i = i + 1
t=a+b
*i = t
*i = t
if i<N goto L2
if i<N goto L2
L3: x = t
L3: x = t
[email protected] 05/07/2023 23
Loop Optimization - Strength Reduction
● replacing expensive operations with cheaper ones like multiplication is costlier
than addition
After optimization:
Before optimization:
Expensive Cheaper
t= 3 * x+1;
while (x<10) x2 x*x
while (x<10)
{
{ 2*x x+x
y := 3 * x+1;
y=t;
a[y] := a[y]-2; x/2 x * 0.5
a[y]= a[y]-2;
x := x+2;
x=x+2;
}
t=t+6;
}
[email protected] 05/07/2023 24
Loop Optimization - Loop Peeling
● a loop with problematic iteration is resolved separately before entering the
loop
[email protected] 05/07/2023 25
Principle Sources of Optimization - Causes of Redundancy
● redundancy is a side e ect of having written the program in a high-level
language.
● Consider the code fragment for Quick Sort
[email protected] 05/07/2023 26
Principle Sources of Optimization - Causes of Redundancy
● 3-address Code for the code Fragment of Quick Sort
[email protected] 05/07/2023 27
Principle Sources of Optimization - Causes of Redundancy
[email protected] 05/07/2023 28