title: Why is my Python NumPy code faster than C++?
body: <p>Why is this Python NumPy code,</p>
  <pre><code>import numpy as np
  import time
  
  k_max = 40000
  N = 10000
  
  data = np.zeros((2,N))
  coefs = np.zeros((k_max,2),dtype=float)
  
  t1 = time.time()
  for k in xrange(1,k_max+1):
      cos_k = np.cos(k*data[0,:])
      sin_k = np.sin(k*data[0,:])
      coefs[k-1,0] = (data[1,-1]-data[1,0]) + np.sum(data[1,:-1]*(cos_k[:-1] - cos_k[1:]))
      coefs[k-1,1] = np.sum(data[1,:-1]*(sin_k[:-1] - sin_k[1:]))
  t2 = time.time()
  
  print('Time:')
  print(t2-t1)
  </code></pre>
  <p>faster than the following C++ code?</p>
  <pre><code>#include &lt;cstdio&gt;
  #include &lt;iostream&gt;
  #include &lt;cmath&gt;
  #include &lt;time.h&gt;
  
  using namespace std;
  
  // consts
  const unsigned int k_max = 40000;
  const unsigned int N = 10000;
  
  int main()
  {
      time_t start, stop;
      double diff;
      // table with data
      double data1[ N ];
      double data2[ N ];
      // table of results
      double coefs1[ k_max ];
      double coefs2[ k_max ];
      // main loop
      time( &amp; start );
      for( unsigned int j = 1; j&lt;N; j++ )
      {
          for( unsigned int i = 0; i&lt;k_max; i++ )
          {
              coefs1[ i ] += data2[ j-1 ]*(cos((i+1)*data1[ j-1 ]) - cos((i+1)*data1[ j ]));
              coefs2[ i ] += data2[ j-1 ]*(sin((i+1)*data1[ j-1 ]) - sin((i+1)*data1[ j ]));
          }
      }
      // end of main loop
      time( &amp; stop );
      // speed result
      diff = difftime( stop, start );
      cout &lt;&lt; &quot;Time: &quot; &lt;&lt; diff &lt;&lt; &quot; seconds&quot;;
      return 0;
  }
  </code></pre>
  <p>The first one shows: &quot;Time: 8 seconds&quot;
  while the second: &quot;Time: 11 seconds&quot;</p>
  <p>I know that NumPy is written in C, but I would still think that C++ example would be faster. Am I missing something? Is there a way to improve the C++ code (or the Python one)?</p>
  <h3>Version 2 of the code</h3>
  <p>I have changed the C++ code (dynamical tables to static tables) as suggested in one of the comments. The C++ code is faster now, but still much slower than the Python version.</p>
  <h3>Version 3 of the code</h3>
  <p>I have changed from debug to release mode and increased 'k' from 4000 to 40000. Now NumPy is just slightly faster (8 seconds to 11 seconds).</p>