title: C++ - Improve computation time for complex number math
body: <p>I am trying to calculate complex numbers for a 2D array in C++. The code is running very slowly and I have narrowed down the main cause to be the exp function (the program runs quickly when I comment out that line, even though I have 4 nested loops). </p>
  
  <pre><code>int main() {
  
      typedef vector&lt; complex&lt;double&gt; &gt; complexVect;
      typedef vector&lt;double&gt; doubleVect;
  
      const int SIZE = 256;
      vector&lt;doubleVect&gt; phi_w(SIZE, doubleVect(SIZE));
      vector&lt;complexVect&gt; phi_k(SIZE, complexVect(SIZE));
      complex&lt;double&gt; i (0, 1), cmplx (0, 0);
      complex&lt;double&gt; 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&lt;double&gt; arg3;
      double angle;
      vector&lt;complexVect&gt; newImg(SIZE, complexVect(SIZE));
  
      for (x = 0; x &lt; SIZE; ++x) {
          xPos = -127 + x;
          for (y = 0; y &lt; SIZE; ++y) {
              yPos = -127 + y;
              for (t = 0; t &lt; SIZE; ++t) {
                  temp = cmplx;
                  angle = dt * t;
                  arg = xPos * cos(angle) + yPos * sin(angle);
                  for (k = 0; k &lt; 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;
          }
      }
  }
  </code></pre>
  
  <p>Is there a way I can improve computation time? I have tried using the following helper function but it doesn't noticeably help. </p>
  
  <pre><code>complex&lt;double&gt; complexexp(double arg) {
      complex&lt;double&gt; temp (sin(arg), cos(arg));
      return temp;
  }
  </code></pre>
  
  <p>I am using clang++ to compile my code</p>
  
  <p>edit: I think the problem is the fact that I'm trying to calculate complex numbers. Would it be faster if I just used Euler's formula to calculate the real and imaginary parts in separate arrays and not have to deal with the complex class?</p>