您的位置:首页 > 其它

关于卡马克算法和系统函数库方法快速开平方根快慢的研究

2016-12-08 01:13 441 查看
class MyMath
{
public:
float GetSqrtMy(float num);
float GetSqrtSys(float num);
private :
long i;
float x2, y;
const float threehalfs = 1.5F;
};


#include "MyMath.h"
#include <iostream>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<cfloat>

float MyMath::GetSqrtMy(float number)
{
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));
y = y * (threehalfs - (x2 * y * y));
y = y * (threehalfs - (x2 * y * y));
return y*number;
}
float MyMath::GetSqrtSys(float number)
{
float sq = sqrt(number);
return sq;
}

#include "MyMath.h"
#include <iostream>
#include <ctime>

int main()
{
clock_t startTime, endTime;
MyMath* myMath = new MyMath();
int res = 0;
long average = 0l;
for (int count = 0; count < 10; count++)
{
startTime = clock();
for (int i = 0; i < 100000000; i++)
{
res = myMath->GetSqrtSys(float(i));
}
endTime = clock();
average += endTime - startTime;
}
printf("res = %d,start = %ld, end = %ld,sys = %ld\n", res, startTime, endTime, average / 10);

average = 0l;
for (int count = 0; count < 10; count++)
{
startTime = clock();
for (int i = 0; i < 100000000; i++)
{
res = myMath->GetSqrtMy(float(i));
}
endTime = clock();
average += endTime - startTime;
}
printf("res = %d,start = %ld, end = %ld, my = %ld\n", res, startTime, endTime, average / 10);
}

release编译结果(10次求平均值):
x86



x64



但是下午在公司电脑上测试的,当release时,卡马克的更快,大概快不到一倍,在debug,系统函数要快。但是在我自己电脑上却是上面的结果。很奇怪。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: