FAST_DIVIDE32(3)
π 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
- nixpkgs unstable: netbsd-source 11.0
- Copyright (c) 2010 The NetBSD Foundation, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms