python - 为什么这个双循环在 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
.
解决方案
推荐阅读
- c# - 如何在打开 MdiChild 表单后立即关闭它?
- wso2 - wso2 revoke api 没有撤销令牌
- java - 在文件基础服务上执行 junit 时出现 IOException
- robotframework - 将带括号的路径参数传递给 MS DOS 批处理文件
- go - 如何在golang中的F2()之前调用函数F1()
- git - 有没有办法将 git 中的现有文件复制到同一分支中的新文件夹并保留历史记录
- postgresql - 如何从嵌套的多对多连接中获取唯一值
- python - 如何过滤掉其中包含区域字段的字典并放入新的 json 文件
- python - OpenCV检测手写等号运算符错误
- c# - if 语句和负整数的问题