Search code examples
coptimizationloop-unrolling

Unrolling For Loop in C


I am trying to unroll this loop by a factor of 2.

for(i=0; i<100; i++){
  x[i] = y[i] + z[i];
  z[i] = y[i] + a[i];
  z[i+1] = y[i] * a[i];
}

I have it unrolled to:

 for(i=0; i<100; i+=2){
   x[i] = y[i] + z[i];
   x[i+1] = y[i+1] + z[i+1];
   z[i] = y[i] + a[i];
   z[i+1] = y[i] * a[i];
 }

I'm not sure how to unroll the lines for z[i] as the original for loop already has z[i+1]. Can anyone help me understand this?


Solution

  • I'd say simply add the lines for i+1. But you have to be sure they are in the right order, so:

     for(i=0; i<100; i+=2){
        x[i] = y[i] + z[i];
        z[i] = y[i] + a[i];
        z[i+1] = y[i] * a[i];
    
        // next iteration
        if (i+1 < 100) {
              x[i+1] = y[i+1] + z[i+1];
              z[i+1] = y[i+1] + a[i+1];
              z[i+2] = y[i+1] * a[i+1]; 
        }
     }
    

    EDIT

    to make it safe for all upper bounds (not only even) you have to add an if in the loop

    As Adrian Mole mentions, it could be better to check the upper bound in the first place or set the size of the array conveniently