[Numpy-discussion] Faster
Keith Goodman
kwgoodman at gmail.com
Sun May 4 12:20:32 EDT 2008
On Fri, May 2, 2008 at 7:25 PM, Robert Kern <robert.kern at gmail.com> wrote:
> Assuming x is contiguous and you can modify x in-place:
>
>
> In [1]: from numpy import *
>
> In [2]: def dist(x):
> ...: x = x + 1e10 * eye(x.shape[0])
> ...: i, j = where(x == x.min())
>
> ...: return i[0], j[0]
> ...:
>
> In [3]: def symmdist(N):
> ...: x = random.rand(N, N)
> ...: x = x + x.T
> ...: x.flat[::N+1] = 0
> ...: return x
> ...:
>
> In [4]: symmdist(5)
> Out[4]:
> array([[ 0. , 0.87508654, 1.11691704, 0.80366071, 0.57966808],
> [ 0.87508654, 0. , 1.5521685 , 1.74010886, 0.52156877],
> [ 1.11691704, 1.5521685 , 0. , 1.22725396, 1.04101992],
> [ 0.80366071, 1.74010886, 1.22725396, 0. , 1.94577965],
> [ 0.57966808, 0.52156877, 1.04101992, 1.94577965, 0. ]])
>
> In [5]: def kerndist(x):
> ...: N = x.shape[0]
> ...: x.flat[::N+1] = x.max()
> ...: ij = argmin(x.flat)
> ...: i, j = divmod(ij, N)
> ...: return i, j
> ...:
>
> In [10]: x = symmdist(500)
>
> In [15]: %timeit dist(x)
> 10 loops, best of 3: 19.9 ms per loop
>
> In [16]: %timeit kerndist(x)
> 100 loops, best of 3: 4.38 ms per loop
I added
i, j = divmod(x.argmin(), x.shape[0])
to
http://scipy.org/PerformanceTips
More information about the NumPy-Discussion
mailing list