C循环的优化

Optimization of C loop

我有以下计算系数的函数:

void CalculateCoefficients(LinearFit *DataSet, double *A, double *B)
  {
   /* Declare and initialize sum variables */
   double S_XX = 0.0;
   double S_XY = 0.0;
   double S_X  = 0.0;
   double S_Y  = 0.0;
   int lcv;

   /* Compute the sums */
   for (lcv=0; lcv < DataSet->NextElement; lcv++)
    {
      S_XX += DataSet->Data_X[lcv] * DataSet->Data_X[lcv];
      S_XY += DataSet->Data_X[lcv] * DataSet->Data_Y[lcv];
      S_X  += DataSet->Data_X[lcv];
      S_Y  += DataSet->Data_Y[lcv];
    } /* for() */

   /* Compute the parameters of the line Y = A*X + B */
   (*A) = (((DataSet->NextElement * S_XY) - (S_X * S_Y)) / ((DataSet->NextElement * S_XX) - (S_X * S_X)));
   (*B) = (((S_XX * S_Y) - (S_XY * S_X)) / ((DataSet->NextElement * S_XX) - (S_X * S_X)));
  } /* CalculateCoefficients() */

我正在寻求优化循环。我试过循环展开,但效果不大。我还能做什么?

你可以试试:

double dsdx, dsdy;
...
dsdx = DataSet->Data_X[lcv];
dsdy = DataSet->Data_y[lcv];
S_XX += dsdx * dsdx;
S_XY += dsdx * dsdy;
S_X  += dsdx;
S_Y  += dsdy;
...

这样,在循环的每次迭代中,您只能从结构中获取一次值。