快速开方之魔法数 0x5f3759df

一、快速开方之魔法数 0x5f3759df

测试代码:

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

#define N_NUM 2147483640

float Q_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
//	y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

//#ifndef Q3_VM
//#ifdef __linux__
//	assert( !isnan(y) ); // bk010122 - FPE?
//#endif
//#endif
	return y;
}

int main()
{
	int i, j;
	float res;

	struct timeval start, end;
	int timeuse;

	printf("%f\n", 1.0/Q_rsqrt(3.14159));
	printf("%f\n", sqrt(3.14159));
	printf("%f\n", 1.0/Q_rsqrt(100));
	printf("%f\n", sqrt(100));

	gettimeofday(&start, NULL);
	for(i=0; i<N_NUM; i++){
		//for(j=0; j<N_NUM; j++) {
			res=1.0/Q_rsqrt(i);
			//res=0;
		//}
	}
	gettimeofday(&end, NULL);
	timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec;
	printf("time1=%.3fs\n", (double)timeuse/1000000);

	printf("done\n");
	gettimeofday(&start, NULL);
	for(i=0;i<N_NUM;i++){
		//for(j=0; j<N_NUM; j++) {
			res=sqrt(i);
			//res=0;
		//}
	}
	gettimeofday(&end, NULL);
	timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec;
	printf("time2=%.3fs\n", (double)timeuse/1000000);

    return 0;
}

运行结果:

1.773184

1.772453

10.015536

10.000000

time1=0.000s

done

time2=3.439s //耗时差距很大

相关推荐
那个村的李富贵5 小时前
CANN加速下的AIGC“即时翻译”:AI语音克隆与实时变声实战
人工智能·算法·aigc·cann
power 雀儿5 小时前
Scaled Dot-Product Attention 分数计算 C++
算法
琹箐6 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
renhongxia16 小时前
如何基于知识图谱进行故障原因、事故原因推理,需要用到哪些算法
人工智能·深度学习·算法·机器学习·自然语言处理·transformer·知识图谱
坚持就完事了6 小时前
数据结构之树(Java实现)
java·算法
算法备案代理6 小时前
大模型备案与算法备案,企业该如何选择?
人工智能·算法·大模型·算法备案
赛姐在努力.7 小时前
【拓扑排序】-- 算法原理讲解,及实现拓扑排序,附赠热门例题
java·算法·图论
野犬寒鸦8 小时前
从零起步学习并发编程 || 第六章:ReentrantLock与synchronized 的辨析及运用
java·服务器·数据库·后端·学习·算法
霖霖总总8 小时前
[小技巧66]当自增主键耗尽:MySQL 主键溢出问题深度解析与雪花算法替代方案
mysql·算法
rainbow68898 小时前
深入解析C++STL:map与set底层奥秘
java·数据结构·算法