一个超级快速的开平方根C函数

一个超级快速的开平方根C函数

#include <stdio.h>
#include <time.h>
//#define TEST_Q
//#define TEST_MATH 1
#define TEST_SSE 1


#ifdef TEST_Q 
float new_rsqrt( float number ) //这是卡马克大神级别的优化
{
    long i;
    float x2, y;
    const float threehalfs = 1.5F;
   
    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;      // evil floating point bit level hacking
    i  = 0x5f3759df - ( i >> 1 );               // what the fuck?
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration

    return y;
}
#endif

#ifdef TEST_MATH
#include <math.h>

float new_rsqrt(float f){ //这是调用标准的math.h函数库
   
    return 1/sqrtf(f);
}
#endif

#ifdef TEST_SSE
#include <xmmintrin.h>
float new_rsqrt(float f){ //这是调用用CPU SSE指令集中rsqrt函数直接得出结果
   
    __m128 m_a = _mm_set_ps1(f);
    __m128 m_b = _mm_rsqrt_ps(m_a);
   
    return m_b[0];
}
#endif


int main(int argc, const char * argv[]) {
   
    int i ;
    float r;
    printf("%f\n", new_rsqrt(9)); //因为结果应该是1/3,无限循环,用以对比精度
    clock_t start_time = clock();
    for (i=0;i< 0xfffffff; i++){
        r = new_rsqrt(i);
    }
   
    printf("Time cost: %ld ns\n", clock() - start_time);
}

LitrindeMacBook-Pro:~ litrin$ time ./test_q
0.332953
Time cost: 7746636 ns

real 0m7.773s
user 0m7.733s
sys 0m0.019s
LitrindeMacBook-Pro:~ litrin$ time ./test_sse
0.333252
Time cost: 1391658 ns

real 0m1.399s
user 0m1.391s
sys 0m0.005s
LitrindeMacBook-Pro:~ litrin$ time ./test_normal
0.333333
Time cost: 3882738 ns

real 0m3.892s
user 0m3.879s
sys 0m0.009s

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汪宁宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值