How to make this speed up

Anton Vredegoor anton at vredegoor.doge.nl
Wed Mar 31 17:55:12 CEST 2004


Carl Banks wrote:

>    def distance(a,b):
>        x = a[0] - b[0]
>        y = a[1] - b[1]
>        z = a[2] - b[2]
>        return sqrt(x*x + y*y + z*z)

This gives a nice speedup (about 2 times). However, using psyco -and
using x*x instead of x**2- results in more than 10 times faster code
on my machine, without losing the option of having a variable number
of dimensions:

from random import uniform
from math import sqrt
from time import time

def random_points(limits,dims,n):
    def u(): 
        return [uniform(*limits) 
            for i in range(dims)]
    return [u() for i in xrange(n)]
        
def distance(a,b):
    d = 0
    for i in range(len(a)):
        x = a[i]-b[i]
        d += x*x
    return sqrt(d)

def compute_distances(plist):
    result = []
    for i in range(len(plist)-1):
        for j in range(i+1,len(plist)):
            result.append(distance(plist[i],plist[j]))
    return result

def test():
    n = 500
    P = random_points([0,1000],3,n)
    t = time()
    D1 = compute_distances(P)
    print time()-t
    import psyco
    psyco.full()
    t = time()
    D2 = compute_distances(P)
    print time()-t
    assert D1==D2

if __name__=='__main__':
    test()

output:

4.77999997139
0.389999866486


Anton







More information about the Python-list mailing list