Today I learned about Duff's Device
...on Sep 1, 2021A fellow was credited with inventing something that other people discovered on their own
I was reading a paper1 on C’s evolution from necessary systems programming that referenced and gave an example of Duff’s Device. The basic gist is that it was a form of loop unrolling so that the loop’s condition didn’t need to be evaluated on each iteration. The example was essentially using a switch
statement and case fall-through, or some operation that a compiler might optimize in the wrong way.
Sitting by myself in 1985, creating a high-speed text library for the IBM PC, I had discovered something similar but it was relatively straightforward to me since I was using assembly language. My version was approximately this (I no longer have any of this code, so this2 is just a junky facsimile from the back of my head):
...
CLOCK_MODULUS DB 04Bh ; because there's always a magic number, right?
...
MOV DX, CLOCK_MODULUS ; we want to get the modulus (remainder)
AND DX, 07h ; after taking the value and seeing how many bits are left
MOV DI, UNROLLED ; so DI has the base of the sequence operations
ADD DI, DX ; and DX has the number of low-order bits remaining
JMP [DI] ; so this is where we jump to shift by the number of bits
UNROLLED:
SHL AX, 1 ; series of shifts...because reasons
SHL AX, 1
SHL AX, 1
SHL AX, 1
SHL AX, 1
SHL AX, 1
SHL AX, 1
...
I’m clear that I wasn’t brilliant, and didn’t spend months researching this. It was just a random insight. I find it funny that we go on ‘reinventing the wheel’ out of obviousness, and often someone else comes along and names it. You can be that person, if you write it down somewhere and get the right kind of attention.
Notes
-
Stephen Kell, 2017. Some Were Meant for C ↩
-
There is NO WAY this code assembles or even has useful meaning. ↩