In [2]:
import math
import numpy as np

def closest(pos, points):
    x0, y0 = pos
    dbest, ibest = None, None
    for i, (x, y) in enumerate(points):
        d = (x - x0) ** 2 + (y - y0) ** 2
        if dbest is None or d < dbest:
            dbest, ibest = d, i

    return dbest, ibest

ref = .5, .5
points = np.random.rand(10 ** 6, 2)
print(points.ndim)
print(points.shape)
print(points)

%timeit closest(ref, points)
print(closest(ref, points))


2
(1000000, 2)
[[ 0.59472432  0.46514771]
 [ 0.98183227  0.18811625]
 [ 0.82474897  0.04614071]
 ..., 
 [ 0.61934535  0.78967652]
 [ 0.48760346  0.0972289 ]
 [ 0.1589388   0.30518495]]
1 loops, best of 3: 2.99 s per loop
(7.9453597471512363e-08, 820675)

In [3]:
def np_closest(pos, points):
    x, y = points[:,0], points[:,1]
    distances = (x - pos[0]) ** 2 + (y - pos[1]) ** 2
    ibest = distances.argmin()
    dbest = distances[ibest]
    return dbest, ibest

%timeit np_closest(ref, points)
print(np_closest(ref, points))


100 loops, best of 3: 13 ms per loop
(7.9453597471512363e-08, 820675)