Skip to content

Instantly share code, notes, and snippets.

@akpoff
Created August 15, 2024 05:39
Show Gist options
  • Save akpoff/14749fd4ee1d175090353cecfbc5322b to your computer and use it in GitHub Desktop.
Save akpoff/14749fd4ee1d175090353cecfbc5322b to your computer and use it in GitHub Desktop.
Duff's Device in Python
def duffs_device(frm, count):
"""
Implement Duff's Device for copying frm in a loop-unrolled fashion.
:param frm: List or array-like object to copy frm
:param count: Number of elements to copy
"""
# Ensure we have at least one element to copy
if count <= 0:
return
# Number of integral groups of 8 to copy
n = (count + 7) // 8
remainder = count % 8
while n > 0:
# First pass through will be remainder elements
# Pop 0th element to mimic reading from source
# Uses print() as the destination
if remainder == 0:
print(frm.pop(0), "", end='')
if remainder >= 1 or remainder == 0:
print(frm.pop(0), "", end='')
if remainder >= 2 or remainder == 0:
print(frm.pop(0), "", end='')
if remainder >= 3 or remainder == 0:
print(frm.pop(0), "", end='')
if remainder >= 4 or remainder == 0:
print(frm.pop(0), "", end='')
if remainder >= 5 or remainder == 0:
print(frm.pop(0), "", end='')
if remainder >= 6 or remainder == 0:
print(frm.pop(0), "", end='')
if remainder == 7 or remainder == 0:
print(frm.pop(0), "", end='')
print()
# remainder handled, reset to 0
remainder = 0
n -= 1
# Example usage:
frm = list(range(1000)) # A list of numbers frm 0 to 999
duffs_device(frm, 300) # Copy out n elements to sink
@akpoff
Copy link
Author

akpoff commented Aug 15, 2024

I wrote this as an example in response to a post I made on X as a contrast to code from Grok. Yes, it's a nutty idea. See the original post.

https://x.com/akpoff/status/1823958893292130430

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment