Is it possible to write Quake's fast InvSqrt() function in Rust?

前端 未结 3 1393
太阳男子
太阳男子 2021-01-29 23:03

This is just to satisfy my own curiosity.

Is there an implementation of this:

float InvSqrt (float x)
{
   float xh         


        
3条回答
  •  被撕碎了的回忆
    2021-01-29 23:42

    This one is implemented with less known union in Rust:

    union FI {
        f: f32,
        i: i32,
    }
    
    fn inv_sqrt(x: f32) -> f32 {
        let mut u = FI { f: x };
        unsafe {
            u.i = 0x5f3759df - (u.i >> 1);
            u.f * (1.5 - 0.5 * x * u.f * u.f)
        }
    }
    

    Did some micro benchmarks using criterion crate on a x86-64 Linux box. Surprisingly Rust's own sqrt().recip() is the fastest. But of course, any micro benchmark result should be taken with a grain of salt.

    inv sqrt with transmute time:   [1.6605 ns 1.6638 ns 1.6679 ns]
    inv sqrt with union     time:   [1.6543 ns 1.6583 ns 1.6633 ns]
    inv sqrt with to and from bits
                            time:   [1.7659 ns 1.7677 ns 1.7697 ns]
    inv sqrt with powf      time:   [7.1037 ns 7.1125 ns 7.1223 ns]
    inv sqrt with sqrt then recip
                            time:   [1.5466 ns 1.5488 ns 1.5513 ns]
    

提交回复
热议问题