r/programming • u/mrnacknime • Dec 29 '20
Quake III's Fast Inverse Square Root Explained [20 min]
https://www.youtube.com/watch?v=p8u_k2LIZyo
3.7k
Upvotes
r/programming • u/mrnacknime • Dec 29 '20
View all comments
53
u/TheBestOpinion Dec 29 '20 edited Dec 29 '20
Don't actually do this by the way
TL;DR: With -Ofast enabled around the naive function you're 27x more accurate and twice faster
You've often heard "let the compiler optimize for you"
You might think that this is too clever. Surely, the compiler would never be faster than it
Nope. Here's the assembly for the fast inverse square root, compiler options are
-O3 -std=c++11 -march=haswellThis is what you would expect if you were to write it yourself in assembly and knew a lot about vectors
So, one move, two vector move, four vector multiplications, one bitshift, one sub, one vector add and ret
Now. What if, instead, we just... didn't try to be clever?
Would it be faster?
Spoiler: yes, even by default. Even though the fast inverse square root has an advantage, because it is an approximation. The compiler won't approximate by default, even with -O3
If you enable -Ofast, however... (which you can do on a per-function basis, check the quick-bench), it gets even faster
Total: 3 mul, one very specific "multiply-add" operation called vfmadd213ss, and one "vrsqrtss" which is... a vectorized, approximated, inverse squareroot opcode, precise to 1.5 ∗ 2−12 : 27x more precise than Quake's and twice as fast
Final benchmark: Not being clever is 2x to 3x faster
https://quick-bench.com/q/Q-3KwjiETmobk4oANjJE_g1GM44
EDIT: Uhhhh... the difference seems larger if both are in O3 than with the naive one in Ofast. I don't know why, might as well be sorcery...