I'm trying to analyze some data, for which I need to calculate a quantity involving a double sum. The python code looks like this:
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
This takes roughly 1.5s
to run. This is 10 times more time than MATLAB takes to do the same computation:
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
Outputting:
>> speedTest
Elapsed time is 0.096789 seconds.
Why is my python script so slow? How can I make it run as fast as the MATLAB script? (And yes, I have to do this in python for a number of other reasons)
Mind that the real data corresponds to an array size of >10,000
elements, so the time different becomes radically large, as the number of flops scale quadratically with the number of elements.
EDIT:
I tried the same without numpy
(except for random number generation), using solely lists:
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
This results in:
$ time python3 speedAutoCorr2.py
real 0m6.510s
user 0m6.731s
sys 0m0.123s
which is even worse than the case with numpy
.