FAST_DIVIDE32(3)

πŸ“¦ version 11.0, in nixpkgs unstable

πŸ’… FAST_DIVIDE32(3) β€” library functions manual, section 3, bestie

okay so picture this: you're in a <sys/bitops.h> kind of mood and you need to divide a 32-bit number but like... faster. that's the whole vibe here. three little functions, one header, zero drama. let's get into it ✨


🌸 NAME 🌸

fast_divide32, fast_divide32_prepare, fast_remainder32 β€” fast 32bit division and remainder, no cap 🫢


πŸŽ€ SYNOPSIS πŸŽ€

#include <sys/bitops.h>

uint32_t
fast_divide32(uint32_t v, uint32_t div, uint32_t m, uint8_t s1,
    uint8_t s2);

uint32_t
fast_remainder32(uint32_t v, uint32_t div, uint32_t m, uint8_t s1,
    uint8_t s2);

void
fast_divide32_prepare(uint32_t div, uint32_t *m, uint8_t *s1,
    uint8_t *s2);

like, that's the whole contract. sign it. πŸ’…


πŸ’– DESCRIPTION πŸ’–

so fast_divide32 and fast_remainder32 do the exact same thing as v / div and v % div, except they're using optimised CPU instructions to do it and it's giving main character energy πŸ”₯

but β€” and this is the part where you have to pay attention bestie β€” the constants m, s1, and s2 must first be preset for a given value of div with the fast_divide32_prepare function. like, you cannot skip that step, that's not a suggestion, that's a requirement periodt πŸ™ˆ


πŸ¦‹ RATIONALE πŸ¦‹

why do these exist? inner loops and other performance-sensitive tasks, obviously. that's their whole thing ⭐

the functions expand to code that's typically slightly larger than a plain division instruction, but it requires less time to execute β€” so you're trading a lil bit of code size for speed and honestly? worth it. slay πŸ’…

also, fun fact: the code for constant div arguments should be equivalent to the assembly created by GCC. iconic. no notes. πŸ‘‘


🌈 EXAMPLES 🌈

the following example computes q = a / b and r = a % b:

uint32_t a, b, q, r, m;
uint8_t s1, s2;

fast_divide32_prepare(b, &m, &s1, &s2);

q = fast_divide32(a, b, m, s1, s2);
r = fast_remainder32(a, b, m, s1, s2);

see? prepare first, then divide, then remainder. in that order. always. that's the whole routine bestie πŸŽ€


✨ SEE ALSO ✨

and also this absolute banger of a paper, like the way that these two went off:

TorbjΓΆrn Granlund and Peter L. Montgomery, β€œDivision by Invariant Integers Using Multiplication”, ACM SIGPLAN Notices, Issue 6, Volume 29, https://gmplib.org/~tege/divcnst-pldi94.pdf, 61-72, June 1994. πŸ“š

like genuinely, if you're the kind of person who reads papers for fun (respect), this one ate. πŸ”₯


🧚 HISTORY 🧚

the fast_divide32 function appeared in NetBSD 6.0. so it's been serving looks since 2012-ish, we love a legacy queen πŸ‘‘


kisses and good vibes only β€” this page came to you from Debian, dated May 10, 2011, and yes she's still cute all these years later πŸ’–βœ¨πŸŽ€

πŸ“¦ where this page comes from