快速sin cos

在优化算法时时间项费非常关键,如果需要大量使用sin cos,那么对sin cos的优化将大大提高运算速度

最近发现一个快速计算sin cos的方法,


#include"cmath"
#include<iostream>
#include<cstdio>
#include<ctime>
using namespace std;
#define MILLION 1000000


#define CV_PI 3.14159265359
#define halfPi ((float)(CV_PI*0.5))
#define Pi     ((float)CV_PI)
#define a0  0 /*-4.172325e-7f*/   /*(-(float)0x7)/((float)0x1000000); */
#define a1 1.000025f        /*((float)0x1922253)/((float)0x1000000)*2/Pi; */
#define a2 -2.652905e-4f    /*(-(float)0x2ae6)/((float)0x1000000)*4/(Pi*Pi); */
#define a3 -0.165624f       /*(-(float)0xa45511)/((float)0x1000000)*8/(Pi*Pi*Pi); */
#define a4 -1.964532e-3f    /*(-(float)0x30fd3)/((float)0x1000000)*16/(Pi*Pi*Pi*Pi); */
#define a5 1.02575e-2f      /*((float)0x191cac)/((float)0x1000000)*32/(Pi*Pi*Pi*Pi*Pi); */
#define a6 -9.580378e-4f    /*(-(float)0x3af27)/((float)0x1000000)*64/(Pi*Pi*Pi*Pi*Pi*Pi); */

#define _sin(x) ((((((a6*(x) + a5)*(x) + a4)*(x) + a3)*(x) + a2)*(x) + a1)*(x) + a0)
#define _cos(x) _sin(halfPi - (x))

int main(){
    struct timespec tpstart;
    struct timespec tpend;
    long timedif;


	//fastsin cos
	{
		
		float sine, cose;
		float dsin, dcos;
		clock_gettime(CLOCK_MONOTONIC, &tpstart);
		for(float ang = 0.0; ang < CV_PI; ang += 0.0001)
		{
			sine = _sin(ang);
			cose = _cos(ang);		
		}
		clock_gettime(CLOCK_MONOTONIC, &tpend);
        timedif = MILLION*(tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000;
        printf("it took %ld microseconds\n", timedif);
	}	
	//sin cos
	{
		double sine,cose;
		clock_gettime(CLOCK_MONOTONIC, &tpstart);
		for(double ang = 0.0; ang < CV_PI; ang += 0.0001)
		{
			sine = sin(ang);
			cose = cos(ang);
		}
		clock_gettime(CLOCK_MONOTONIC, &tpend);
        timedif = MILLION*(tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000;
        printf("it took %ld microseconds\n", timedif);
	}	
	return 0;
}

Makefile文件

fastsin : fastsin.cpp
	g++ -o fastsin fastsin.cpp -lrt
clean:
	rm -f fastsin

计算结果:

it took 1300 microseconds
it took 6297 microseconds

系统自带的sin cos计算(double),大概是快速sin cos计算(float)时间的5倍。



  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值