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

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,系统函数要快。但是在我自己电脑上却是上面的结果。很奇怪。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值