for loop in python is 10x slower than matlab

前端 未结 4 1531
庸人自扰
庸人自扰 2020-12-11 06:37

I run python 2.7 and matlab R2010a on the same machine, doing nothing, and it gives me 10x different in speed

I looked online, and heard it should be the same order

4条回答
  •  感情败类
    2020-12-11 07:04

    This is just my opinion, but I think the process is a bit more complex. Basically Matlab is an optimized layer of C, so with the appropriate initialization of matrices and minimization of function calls (avoid "." objects-like operators in Matlab) you obtain extremely different results. Consider the simple following example of wave generator with cosine function. Matlab time = 0.15 secs in practical debug session, Python time = 25 secs in practical debug session (Spyder), thus Python becomes 166x slower. Run directly by Python 3.7.4. machine the time is = 5 secs aprox, so still be a non negligible 33x.

    MATLAB:

    AW(1,:) = [800 , 0    ]; % [amp frec]
    AW(2,:) = [300 , 4E-07]; 
    AW(3,:) = [200 , 1E-06];
    AW(4,:) = [ 50 , 4E-06];
    AW(5,:) = [ 30 , 9E-06];
    AW(6,:) = [ 20 , 3E-05];
    AW(7,:) = [ 10 , 4E-05];
    AW(8,:) = [  9 , 5E-04];
    AW(9,:) = [  7 , 7E-04];
    AW(10,:)= [  5 , 8E-03];
    
    phas    = 0
    
    tini    = -2*365 *86400; % 2 years backwards in seconds
    dt      = 200;        % step, 200 seconds
    tfin    = 0;          % present
    vec_t   = ( tini: dt: tfin)'; % vector_time
    
    nt      = length(vec_t);
    vec_t   = vec_t - phas;
    wave    = zeros(nt,1);
    
    for it = 1:nt
        suma = 0;
        t    = vec_t(it,1);
        for iW = 1:size(AW,1)
            suma = suma + AW(iW,1)*cos(AW(iW,2)*t);
        end
        wave(it,1) = suma;
    end
    

    PYTHON:

    import numpy as np
    
    AW      = np.zeros((10,2))
    AW[0,:] = [800 , 0.0]
    AW[1,:] = [300 , 4E-07]; # [amp frec]
    AW[2,:] = [200 , 1E-06];
    AW[3,:] = [ 50 , 4E-06];
    AW[4,:] = [ 30 , 9E-06];
    AW[5,:] = [ 20 , 3E-05];
    AW[6,:] = [ 10 , 4E-05];
    AW[7,:] = [  9 , 5E-04];
    AW[8,:] = [  7 , 7E-04];
    AW[9,:] = [  5 , 8E-03];
    
    phas    = 0
    
    tini    = -2*365 *86400 # 2 years backwards
    dt      = 200
    tfin    = 0           # present
    nt      = round((tfin-tini)/dt) + 1 
    vec_t   = np.linspace(tini,tfin1,nt) - phas
    
    wave    = np.zeros((nt))
    
    for it in range(nt):
        suma   = 0
        t      = vec_t[fil]
        for iW in range(np.size(AW,0)):
            suma = suma + AW[iW,0]*np.cos(AW[iW,1]*t)
        #endfor iW
        wave[it] = suma
    #endfor it
    

    To deal such aspects in Python I would suggest to compile into executable directly to binary the numerical parts that may compromise the project (or for example C or Fortran into executable and be called by Python afterwards). Of course, other suggestions are appreciated.

提交回复
热议问题