快速开方之魔法数 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 //耗时差距很大

相关推荐
vibecoding日记13 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr213815 小时前
Verilog参数化游程编码RLE模块
算法
望易15 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络19 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹2 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术2 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望2 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法