Why is my Python NumPy code faster than C++?

后端 未结 3 949
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 03:54

Why is this Python NumPy 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 = t         


        
3条回答
  •  遥遥无期
    2021-01-01 04:41

    I tried to understand your Python code and reproduce it in C++. I found that you didn't represent correctly the for-loops in order to do the correct calculations of the coeffs, hence should switch your for-loops. If this is the case, you should have the following:

    #include 
    #include 
    #include 
    
    const int k_max = 40000;
    const int N = 10000;
    
    double cos_k, sin_k;
    
    int main(int argc, char const *argv[])
    {
        time_t start, stop;
        double data[2][N];
        double coefs[k_max][2];
    
        time(&start);
    
        for(int i=0; i

    Switching the for-loops gives me: 3 seconds for C++ code, optimized with -O3, while Python code runs at 7.816 seconds.

提交回复
热议问题