首页 > 解决方案 > 为什么这个双循环在 python 中比 matlab 慢得多?

问题描述

我正在尝试分析一些数据,为此我需要计算一个涉及双倍总和的数量。python代码如下所示:

import numpy as np

tmax = 1000
array = np.random.rand(tmax)

tstart = 500

meanA = np.mean(array[tstart:])

quantity = np.zeros(tmax-tstart)
for f in range(1,tmax-tstart,1):
    count = 0
    integrand = 0

    for ff in range(tstart+1,tmax-f):
            count += 1
            dAt = array[ff] - meanA
            dAtt = array[ff:ff+f+1] - meanA
            integrand += np.sum(dAt * dAtt)

    if count != 0:
            integrand /= f*count
            quantity[f] = integrand

这需要大致1.5s运行。这比 MATLAB 执行相同计算所需的时间多 10 倍:

tic;
tmax = 1000;
tstart = 500;

array = rand(1,tmax);
meanA = mean(array(tstart:tmax));
quantity = zeros(1,tmax);

for f=1:tmax-tstart
    integrand = 0;
    count = 0;
    for ff=tstart:tmax-f
    count = count + 1;
    dAt = array(ff)-meanA;
    dAtt = array(ff:ff+f)-meanA;
    integrand = integrand + sum(dAt*dAtt);
end
integrand = integrand/(f*count);
autocorr(f) = integrand;
end

toc

输出:

>> speedTest
Elapsed time is 0.096789 seconds.

为什么我的 python 脚本这么慢?如何让它像 MATLAB 脚本一样快地运行?(是的,由于许多其他原因,我必须在 python 中执行此操作)

请注意,真实数据对应于元素的数组大小>10,000,因此时间差异变得非常大,因为触发器的数量与元素的数量成二次方关系。

编辑:

numpy我在没有(随机数生成除外)的情况下尝试了相同的方法,仅使用列表:

import numpy as np

tmax = 1000
array = np.random.rand(tmax)

array = list(array)

tstart = 500

meanA = sum((array[tstart:]))/len(array[tstart:])

quantity = [0] * (tmax-tstart)
for f in range(1,tmax-tstart,1):
    count = 0
    integrand = 0

    for ff in range(tstart+1,tmax-f):
            count += 1
            dAt = array[ff] - meanA
            dAtt = array[ff:ff+f+1] - meanA
            try:
                    integrand += sum([dAt * i for i in dAtt])
            except:
                    integrand += dAt * dAtt
    if count != 0:
            integrand /= f*count
            quantity[f] = integrand

这导致:

$ time python3 speedAutoCorr2.py

real    0m6.510s
user    0m6.731s
sys     0m0.123s

这比numpy.

标签: pythonmatlabperformanceloops

解决方案


推荐阅读