2013-04-15 39 views
1

我想在C++中计算二维数组的复数。代码运行速度非常缓慢,我已经将主要原因缩小为exp函数(即使我有4个嵌套循环,当我注释掉该行时,程序会很快运行)。C++ - 改进复杂数学运算的计算时间

int main() { 

    typedef vector< complex<double> > complexVect; 
    typedef vector<double> doubleVect; 

    const int SIZE = 256; 
    vector<doubleVect> phi_w(SIZE, doubleVect(SIZE)); 
    vector<complexVect> phi_k(SIZE, complexVect(SIZE)); 
    complex<double> i (0, 1), cmplx (0, 0); 
    complex<double> temp; 
    int x, y, t, k, w; 
    double dk = 2.0*M_PI/(SIZE-1); 
    double dt = M_PI/(SIZE-1); 
    int xPos, yPos; 
    double arg, arg2, arg4; 
    complex<double> arg3; 
    double angle; 
    vector<complexVect> newImg(SIZE, complexVect(SIZE)); 

    for (x = 0; x < SIZE; ++x) { 
     xPos = -127 + x; 
     for (y = 0; y < SIZE; ++y) { 
      yPos = -127 + y; 
      for (t = 0; t < SIZE; ++t) { 
       temp = cmplx; 
       angle = dt * t; 
       arg = xPos * cos(angle) + yPos * sin(angle); 
       for (k = 0; k < SIZE; ++k) { 
        arg2 = -M_PI + dk*k; 
        arg3 = exp(-i * arg * arg2); 
        arg4 = abs(arg) * M_PI/(abs(arg) + M_PI); 
        temp = temp + arg4 * arg3 * phi_k[k][t]; 
       } 
      } 
      newImg[y][x] = temp; 
     } 
    } 
} 

有没有一种方法可以提高计算时间?我曾尝试使用以下帮助函数,但它并没有明显的帮助。

complex<double> complexexp(double arg) { 
    complex<double> temp (sin(arg), cos(arg)); 
    return temp; 
} 

我使用铛++编译我的代码

编辑:我认为问题是,我试图计算复数的事实。如果我只用欧拉公式来计算单独数组中的实部和虚部并且不必处理复杂类,会更快吗?

回答

0

最昂贵的函数调用为罪()/ COS()。我怀疑用复数参数调用exp()会在后台调用这些函数。

为了保持精度,函数的计算速度非常缓慢,似乎没有办法绕过它。然而,你可以交易准确性的准确性,这似乎是游戏开发者会做的:sin and cos are slow, is there an alternatve?

0

您可以定义数字e为常数,并使用std::pow()功能

+0

为什么会有所作为? – Amit

0

我已经与callgrind看看。唯一略有改善(〜1.3%,大小= 50)我能找到的是改变:

temp = temp + arg4 * arg3 * phi_k[k][t]; 

temp += arg4 * arg3 * phi_k[k][t];