Skip to content

Instantly share code, notes, and snippets.

@smarnach
Created April 2, 2012 12:16
Show Gist options
  • Save smarnach/2283089 to your computer and use it in GitHub Desktop.
Save smarnach/2283089 to your computer and use it in GitHub Desktop.
import timeit
import numpy
import scipy.ndimage.morphology
def f0(a, kernel):
b = numpy.convolve(a, kernel, mode="same") > 1
b[1:] |= b[:-1]
b[:-1] |= b[1:]
return b
def f1(a, kernel):
b = numpy.convolve(a, kernel, mode="same") > 1
return b | numpy.r_[0, b[:-1]] | numpy.r_[b[1:], 0]
def f2(a, kernel):
b = numpy.convolve(a, kernel, mode="same") > 1
return numpy.convolve(b, kernel, mode="same") > 0
def f3(a, kernel):
b = numpy.convolve(a, kernel, mode="same") > 1
return scipy.ndimage.morphology.binary_dilation(b)
def f4(a, kernel):
b = numpy.zeros(a.shape)
for x in range(len(a)-2):
if a[x:x+3].sum()>1:
b[x:x+3]=1
return b
a = numpy.random.randint(2, size=1000000)
kernel = numpy.array([1, 1, 1])
for i in range(5):
fname = "f" + str(i)
print timeit.timeit(fname + "(a, kernel)",
"from __main__ import a, kernel, " + fname,
number=10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment