最近看到一篇文章介绍quake3中的一种快速开方算法,今天测试了一下,结果很奇怪,希望有人能够帮助我解惑。
quake3中求1/sqrt(x)的算法源代码如下(未作任何修改):
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;
}
此算法关键在于0x5f3759df的原理,详细论述我没仔细看,论文在http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf 。
为了测试此算法的实际效果,我在p3 1.2G winxp_home vc6 下进行了测试(用release版本运行!),测试代码如下:
#include <stdio.h>
#include <math.h>
#include <time.h>
#define C_Lib_InvSqrt(f) (1./sqrtf(f))
float InvSqrt(float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x; // get bits for floating value
i = 0x5f3759df - (i>>1); // gives initial guess y0
x = *(float*)&i; // convert bits back to float
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
return x;
}
inline float InvSqrt_inline(float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x; // get bits for floating value
i = 0x5f3759df - (i>>1); // gives initial guess y0
x = *(float*)&i; // convert bits back to float
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
return x;
}
int main(void)
{
float f_1, f_t;
long lCount_1, lCount_2, sum;
time_t tStart, tEnd;
#define TestInvSqrt(func) /
lCount_1 = sum+1;/
tStart = clock();/
while(--lCount_1){lCount_2 = sum+1;while(--lCount_2)f_t = func(f_1);}/
tEnd = clock();/
printf("sum=%d*%d,/tfunction:" #func ",/ttime:%d,/tresult=%f/n", sum, sum, (tEnd - tStart), func(f_1));
sum = 100000000;
f_1 = 6.824;
// TestInvSqrt(InvSqrt);
TestInvSqrt(InvSqrt_inline);
TestInvSqrt(C_Lib_InvSqrt);
return 0;
}
注意:用release版本运行!
结果是:p3 1.2G winxp_home vc6 下release版本,inline函数,运行100000000×100000000次,时间都为0。如果修改为非inline,那么消耗主要在函数调用,不能证明什么。如果改用__int64计数,那么消耗主要在对__int64的计数运算上了,也证明不了什么。如果用debug版本,那么将运行次数降到10000×10000这个量级,倒是可以看出quake3源代码的优势,但为什么速度比release慢了不下10个数量级!?刚才将数量级再提高了8个,测试时间还是0。
问题:
1.为什么10^24次求1/sqrt(x)运算,时间消耗都为0?我想这是vc优化的结果,但奇怪的是,如果我在其中加入了循环计数,其计算次数的确是代码中所表达的次数。
收获:
1.debug与release,inline与非inline对程序的影响可能大于一些优化
2.开发环境对程序效率的影响也较大
3.事情往往不是想的那样,一切皆以实际为准。
本文介绍了在Quake3中用于求1/sqrt(x)的高效算法Q_rsqrt,并通过测试对比了该算法与标准库函数的性能。在特定环境下,尽管Q_rsqrt表现出极高的效率,但在debug模式下或增加计数操作后,性能优势有所下降。测试结果显示开发环境、代码优化和函数调用方式对程序性能有显著影响。
3561





