單片機運行時間優化-M0單片機

//*******************1除法函數*************************
u8 g_inputvalid=1;
/*******************************
first:被除數
second:除數
quotient:商
remainder:餘數
*******************************/

void Division(int first, int second,int *quotient,int *remainder)
{
    u8 flag1,flag2;    
    int temp=second;
    int shift=1;
    
    if(second==0)   //判斷除數是否爲0
    {
        g_inputvalid=0;
        return;
    }

    flag1=1;
    flag2=1;
    if(first<0) //判斷被除數和除數的符號,若爲負數 則轉化爲正數 並且標誌設爲false
    {
        flag1=0;
        first=0-first;
    }
    if(second<0)
    {
        flag2=0;
        second=0-second;
    }
    *quotient=0;
    *remainder=0;

    while(first>=temp)  //通過除數的移位操作來逼近被除數
    {
        temp<<=1;
        if(temp<=first)
            shift<<=1;
        else
        {
            quotient+=shift;
            temp>>=1;
            first-=temp;
            shift=1;
            temp=second;
        }
    }
    *remainder=first;
    if(flag1^flag2)  //如果被除數和除數的符號相異 則商爲負數
        *quotient=0-*quotient;
    if(!flag1) //如果除數或被除數有一個爲負數,則餘數應爲負數
        *remainder=0-*remainder;
}

//**************2整數開平方**************

unsigned short sqrt_ushort(unsigned long a)
{
    unsigned long rem = 0;

    unsigned long root = 0;

    unsigned long divisor = 0;

    int i;

    for(i = 0; i < 16; i++) 
    {
        root <<= 1;
        rem = ((rem << 2) + (a >> 30));
        a <<= 2;
        divisor = (root << 1) + 1;
        if(divisor <= rem) {
            rem -= divisor;
            root++;
        }
  }
  return (unsigned short)(root);
}
 

 

3 乘除法儘量使用位移

 

4 三角函數查表法

//**********sincos數學函數初始化********************
float sin_value[360];
float cos_value[360];

//獲取三角函數轉換數據表
void sin_cos_value_init(void)
{
    int i;

    for(i = 0; i < 360; i++)
    {
        sin_value[i] = sin(i * 3.1415926 / 180);
        cos_value[i] = cos(i * 3.1415926 / 180);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章