This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.


  Unrolling a Loop with Duff's Device
  Submitted by

Here's a handy little C macro for unrolling a loop eight times with Duff's Device.

#define DUFFS_DEVICE(x,size) \
  { \
  if(size  0) \
  { \
    int __DUFFS_DEVICE_count, __DUFFS_DEVICE_n; \
    __DUFFS_DEVICE_count = size; \
    __DUFFS_DEVICE_n = (__DUFFS_DEVICE_count+7)  3; \
    switch (__DUFFS_DEVICE_count & 7) \
    { \
    case 0: do { x; \
    case 7: x; \
    case 6: x; \
    case 5: x; \
    case 4: x; \
    case 3: x; \
    case 2: x; \
    case 1: x; \
      } while (--__DUFFS_DEVICE_n  0); \
    } \
  } \

Sample usage: /* Previous code: for(int i=0; i<size; i++) { *dest++ = *src++; } */ //New code: DUFFS_DEVICE(*dest++ = *src++, size);

Another example: /* Previous code: for(int i=0; i<size; i++) { do_something_given(i); } */ //New code: //Note: for optimal performance, do_something_given() should be inlined DUFFS_DEVICE(do_something_given(i); i++;, size);

Information about and history of Duff's Device (written by Tom Duff) are available at:

In addition, a simple search on google for "Duff's Device" turns up a sizeable number of useful hits.

Clearly, it's quite easy to alter the number of times the loop is unrolled by changing some of the constants and the switch statement. This has been tested with DJGPP and Microsoft Visual C++.

a.k.a. Magic Card

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.


Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.