[Numpy-discussion] Mean of n values within an array

Phil Ruggera pruggera at gmail.com
Sat Jul 29 11:30:55 EDT 2006


I rewrote some python code using numpy to do a performance comparison.
 The results were the opposite of what I wanted.  Numpy was slower
than Python without numpy.  Is there something wrong with my approach?

# mean of n values within an array
import numpy, time
def nmean(list,n):
    a = []
    for i in range(1,len(list)+1):
        start = i-n
        divisor = n
        if start < 0:
            start = 0
            divisor = i
        a.append(sum(list[start:i])/divisor)
    return a

t = [1.0*i for i in range(1400)]
start = time.clock()
for x in range(100):
    nmean(t,50)
print "regular python took: %f sec."%(time.clock() - start)

def numpy_nmean(list,n):
    a = numpy.empty(len(list),dtype=float)
    for i in range(1,len(list)+1):
        start = i-n
        if start < 0:
            start = 0
        a[i-1] = list[start:i].mean(0)
    return a

t = numpy.arange(0,1400,dtype=float)
start = time.clock()
for x in range(100):
    numpy_nmean(t,50)
print "numpy took: %f sec."%(time.clock() - start)


Results:
regular python took: 1.215274 sec.
numpy took: 2.499299 sec.




More information about the NumPy-Discussion mailing list