import timeit, numpy
setup = '''
from __main__ import mc0, mc1, mc2
import random, numpy
random.seed(0)
n = 10**3
data = [random.randint(0, 2**32-1) for _ in range(n)]
np_data = numpy.array([float(x) for x in data])
'''
# your implementation
def mc0(data):
xmean = []
for i in range(len(data)):
xmean.append(0)
for j in range(i+1):
xmean[i] += data[j]
xmean[i] = xmean[i]/(i+1)
return xmean
# my implementation
def mc1(data):
xmean = []
for i, x in enumerate(data):
if i == 0:
new = x
else:
new = x/(i+1) + xmean[i-1] * (i/(i+1))
xmean.append(new)
return xmean
# Donbeo's numpy implementation
def mc2(data):
xmean = numpy.cumsum(data)/numpy.array(range(1, len(data)+1))
return xmean
number = 100
things = [('mc0', 'mc0(data)'),
('mc1', 'mc1(data)'),
('mc2', 'mc2(np_data)')]
for note, call in things:
print('{:20} {}'.format(note,
timeit.timeit(call, setup=setup, number=number)))
結果:
mc0 26.023956370918587
mc1 0.1423197092108488
mc2 0.13584513496654083
有在每次循環迭代重做了x(1)..x(i)
總和不點,如果您已有這種信息,請撥打xmean
。 Donbeo的版本比我剛剛發佈的純Python版本要快一些(對於這些數據,無論如何)比原始版本要快200倍。
謝謝,它確實更快:D – user2863620