快速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倍。



你可能感兴趣的:(快速sin cos)