Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Loop unrolling
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== C example === The following example demonstrates dynamic loop unrolling for a simple program written in [[C (programming language)|C]]. Unlike the assembler example above, pointer/index arithmetic is still generated by the compiler in this example because a variable (i) is still used to address the array element. Full optimization is only possible if absolute indexes are used in the replacement statements. <syntaxhighlight lang="c"> #include <stdio.h> /* The number of entries processed per loop iteration. */ /* Note that this number is a 'constant constant' reflecting the code below. */ enum { BUNCHSIZE = 8 }; int main(void) { int i = 0; /* counter */ int entries = 50; /* total number to process */ /* If the number of elements is not divisible by BUNCHSIZE, */ /* get repeat times required to do most processing in the while loop */ int repeat = (entries / BUNCHSIZE); /* number of times to repeat */ int left = (entries % BUNCHSIZE); /* calculate remainder */ /* Unroll the loop in 'bunches' of 8 */ while (repeat--) { 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 += BUNCHSIZE; } /* 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 */ 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 */ } } </syntaxhighlight> Code duplication could be avoided by writing the two parts together as in [[Duff's device]].
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)