Skip to content

Instantly share code, notes, and snippets.

@dgrant
Created April 15, 2013 08:38
Show Gist options
  • Select an option

  • Save dgrant/5386740 to your computer and use it in GitHub Desktop.

Select an option

Save dgrant/5386740 to your computer and use it in GitHub Desktop.
Just calculating the mean on an array and doing some profiling in Python.
# mean of n values within an array
import numpy, time
listSize = 10000
meanLength = 50
def nmean(list,n):
a = []
for i in xrange(1,len(list)+1):
start = i-n
divisor = n
if start < 0:
start = 0
divisor = i
a.append(sum(list[start:i])/divisor)
print "a=", a
return a
def profile_nmean():
t = [1.0*i for i in xrange(listSize)]
start = time.clock()
answer=nmean(t,meanLength)
def numpy_nmean(list,n):
a = numpy.empty(len(list),dtype=float)
for i in xrange(len(list)):
start = i-n+1
if start < 0:
start = 0
a[i] = list[start:i+1].mean(0)
print "a=", a
return a
def profile_numpy_nmean():
t = numpy.arange(listSize,dtype=float)
start = time.clock()
answer=numpy_nmean(t,meanLength)
def numpy_nmean2(list,n):
a = numpy.empty(len(list),dtype=float)
b = numpy.cumsum(list)
c = concatenate((b[n:],b[:n]))
a[:n] = b[:n]/(i+1)
a[n:] = (b[n:] - c[n:])/(i+1)
print "a=", a
return a
def profile_numpy_nmean2():
t = numpy.arange(listSize,dtype=float)
start = time.clock()
answer=numpy_nmean(t,meanLength)
import hotshot, hotshot.stats
prof = hotshot.Profile('nmean.prof')
prof.runcall(profile_nmean)
prof.close()
prof = hotshot.Profile('numpy_nmean.prof')
prof.runcall(profile_numpy_nmean)
prof.close()
prof = hotshot.Profile('numpy_nmean2.prof')
prof.runcall(profile_numpy_nmean2)
prof.close()
print "profiling results of nmean:"
stats = hotshot.stats.load('nmean.prof')
stats.strip_dirs()
stats.sort_stats('cumulative', 'calls')
stats.print_stats()
print "profiling results of numpy_nmean:"
stats = hotshot.stats.load('numpy_nmean.prof')
stats.strip_dirs()
stats.sort_stats('cumulative', 'calls')
stats.print_stats()
print "profiling results of numpy_nmean2:"
stats = hotshot.stats.load('numpy_nmean2.prof')
stats.strip_dirs()
stats.sort_stats('cumulative', 'calls')
stats.print_stats()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment