Loop Unrolling (original) (raw)

Last Updated : 11 Sep, 2023

Loop unrolling is a loop transformation technique that helps to optimize the execution time of a program. We basically remove or reduce iterations. Loop unrolling increases the program’s speed by eliminating loop control instruction and loop test instructions.Program 1:

CPP `

// This program does not uses loop unrolling. #include<stdio.h>

int main(void) { for (int i=0; i<5; i++) printf("Hello\n"); //print hello 5 times

return 0;

}

`

Program 2:

CPP `

// This program uses loop unrolling. #include<stdio.h>

int main(void) { // unrolled the for loop in program 1 printf("Hello\n"); printf("Hello\n"); printf("Hello\n"); printf("Hello\n"); printf("Hello\n");

return 0;

}

`

Output:

Hello Hello Hello Hello Hello

**Illustration:**Program 2 is more efficient than program 1 because in program 1 there is a need to check the value of i and increment the value of i every time round the loop. So small loops like this or loops where there is fixed number of iterations are involved can be unrolled completely to reduce the loop overhead.

Advantages:

Disadvantages:

Reference: https://en.wikipedia.org/wiki/Loop_unrolling