6 ms·
I've been writing a bunch of branch-free code recently, so I took a crack at it. In my world, data-dependent table lookups might as well be branches, so let's e
by kmowery 12y ago
I've been writing a bunch of branch-free code recently, so I took a crack at it. In my world, data-dependent table lookups might as well be branches, so let's eliminate those as well.
Here's a fizzbuzz(char*, int) function that can accept any number up to 99999999, and will put the correct FizzBuzz result into the provided buffer (either the printed number, "Fizz ", " Buzz", or "FizzBuzz"). As promised, it's loop-free, and as a bonus it should be constant-time as well:
Assembly: http://pastebin.com/EnJEuxnp http://pastebin.com/EnJEuxnp
compiled from this C: http://pastebin.com/PCQQQ2cn http://pastebin.com/PCQQQ2cn
[edit] generated from this Python: http://pastebin.com/ijr3thE2 http://pastebin.com/ijr3thE2
Pastebinned since it's about 700 assembly instructions.
Unrolling the loop and printing to the screen are left as exercises...
- drxzcl 12y agoDo you mind sharing the python as well?
- kmowery 12y agoSure! It's ripped + modified from a project I'm working on, so it's a little messy: http://pastebin.com/ijr3thE2 http://pastebin.com/ijr3thE2
- rertrree 12y agoOops: 0x00000001000015af <fizzbuzz+47>: cmp edx,0x0 ^^^
- kmowery 12y agoIt does a cmp+setz, which isn't a branch (and I believe is constant-time). An x86 branch would be cmp+jne or something similar.
- deleted 12y ago[deleted]