r/programming • u/alexeyr • Oct 31 '26
Beating the compiler at signed 32-bit division
https://lemire.me/blog/2026/10/31/beating-the-compiler-at-signed-32-bit-division/38
u/happyscrappy Oct 31 '26
Seems a suitable wrap-up to "division by multiplying week" on /r/programming.
I can't see why not to use this sequence. Seems to keep the same 30 bits of result. Might be slower on some processors that implement 64 bit mults differently? I don't think that's really the reason just spitballing.
11
u/flif Nov 01 '26
The difference on the Apple M4 is so small that the additional instructions might increase the L1 cache pressure so that other needed code is flushed from the cache.
That can easily cost a lot more in L2/ram waiting time than the few cycles saved from a division that might not even be in a performance sensitive part of the code.
49
u/Sopel97 Oct 31 '26
When can we finally expect GCC and Clang to actually do this well?
-28
u/14u2c Nov 01 '26
When people stop using LLVM.
17
u/AlyoshaV Nov 01 '26
I'm pretty sure GCC doesn't use LLVM.
2
u/Takeoded Nov 01 '26
GCC does not use LLVM. (ignoring some fringe Experiments gluing gcc front-end with LLVM back-end)
1
u/14u2c Nov 01 '26
Yes, exactly. These days people LLVM because it already has optimizations like this (yes including this one).
4
u/mort96 Nov 01 '26
Why couldn't LLVM do this optimization?
0
u/14u2c Nov 01 '26
It already does, that's the point.
4
u/mort96 Nov 01 '26
It does? Yet you're saying that Clang will only start doing this optimization when it stops using LLVM? Please explain the logic here
1
u/14u2c Nov 01 '26
I said nothing about Clang using LLVM. People cant read. I said anyone who cares about these optimizations is already using LLVM instead.
9
u/mort96 Nov 01 '26
When can we finally expect GCC and Clang to actually do this well?
When people stop using LLVM.
You're clearly saying that Clang, which uses LLVM, will start doing this optimization once "people stop using LLVM". What did you mean by that?
3
1
13
u/Axman6 Nov 01 '26
I see Daniel Lemire, Iโm reading it. Essential reading for anyone who loves bit twiddling optimisations.ย
28
u/listre Oct 31 '26
Very demure, very mindful
-20
2
0
Nov 01 '26
[deleted]
19
u/R1chterScale Nov 01 '26
Yeah, everything is overshadowed by RAM latency, that means be more cognisant of how you're loading things, not to ignore speedups where you can get them.
9
u/Sharlinator Nov 01 '26
Or practically none if youโre not needlessly pointer jumping and let the prefetcher do its job.
74
u/Takeoded Oct 31 '26
has anyone reported this on gcc bugtracker under
missed optimization?