[Numpy-discussion] Simple problem. Is it possible without a loop?
Vicente Sole
sole at esrf.fr
Wed Jun 9 11:24:26 EDT 2010
>> ? Well a loop or list comparison seems like a good choice to me. It is
>> much more obvious at the expense of two LOCs. Did you profile the two
>> possibilities and are they actually performance-critical?
>>
>> cheers
>>
The second is between 8 and ten times faster on my machine.
import numpy
import time
x0 = numpy.arange(10000.)
niter = 2000 # I expect between 10000 and 100000
def option1(x, delta=0.2):
y = [x[0]]
for value in x:
if (value - y[-1]) > delta:
y.append(value)
return numpy.array(y)
def option2(x, delta=0.2):
y = numpy.cumsum((x[1:]-x[:-1])/delta).astype(numpy.int)
i1 = numpy.nonzero(y[1:]> y[:-1])
return numpy.take(x, i1)
t0 = time.time()
for i in range(niter):
t = option1(x0)
print "Elapsed = ", time.time() - t0
t0 = time.time()
for i in range(niter):
t = option2(x0)
print "Elapsed = ", time.time() - t0
More information about the NumPy-Discussion
mailing list