Skip to content

Instantly share code, notes, and snippets.

@enjoylife
Created May 18, 2012 07:40
Show Gist options
  • Save enjoylife/2723803 to your computer and use it in GitHub Desktop.
Save enjoylife/2723803 to your computer and use it in GitHub Desktop.
loop unrolling technique
#include<stdio.h>
#define TOGETHER (8)
int main(void)
{
int i = 0;
int entries = 50; /* total number to process */
int repeat; /* number of times for while.. */
int left = 0; /* remainder (process later) */
/* If the number of elements is not be divisible by BLOCKSIZE, */
/* get repeat times required to do most processing in the while loop */
repeat = (entries / TOGETHER); /* number of times to repeat */
left = (entries % TOGETHER); /* calculate remainder */
/* Unroll the loop in 'bunches' of 8 */
while( repeat-- > 0 )
{
printf("process(%d)\n", i );
printf("process(%d)\n", i + 1);
printf("process(%d)\n", i + 2);
printf("process(%d)\n", i + 3);
printf("process(%d)\n", i + 4);
printf("process(%d)\n", i + 5);
printf("process(%d)\n", i + 6);
printf("process(%d)\n", i + 7);
/* update the index by amount processed in one go */
i += TOGETHER;
}
/* Use a switch statement to process remaining by jumping to the case label */
/* at the label that will then drop through to complete the set */
switch (left)
{
case 7 : printf("process(%d)\n", i + 6); /* process and rely on drop through drop through */
case 6 : printf("process(%d)\n", i + 5);
case 5 : printf("process(%d)\n", i + 4);
case 4 : printf("process(%d)\n", i + 3);
case 3 : printf("process(%d)\n", i + 2);
case 2 : printf("process(%d)\n", i + 1); /* two left */
case 1 : printf("process(%d)\n", i ); /* just one left to process */
case 0 : ; /* none left */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment