how to make this code faster

Juho Schultz juho.schultz at helsinki.fi
Thu Oct 13 02:43:48 EDT 2005


ajikoe at gmail.com wrote:
> def f(x,y):
>     return math.sin(x*y) + 8 * x
> I have code like this:
> 
> def main():
>     n = 2000
>     a = zeros((n,n), Float)
>     xcoor = arange(0,1,1/float(n))
>     ycoor = arange(0,1,1/float(n))
> 
> 
>     for i in range(n):
>         for j in range(n):
>             a[i,j] = f(xcoor[i], ycoor[j])  # f(x,y) = sin(x*y) + 8*x
> 
>     print a[1000,1000]
>     pass
> 
> if __name__ == '__main__':
>     main()
> 
> 
> I try to make this run faster even using psyco, but I found this still
> slow, I tried using java and found it around 8x faster...
> 

I guess the double loop (4E6 rounds) makes your program so slow.

I assume you are using numarray or numeric for this.
The built-in array operations are a lot faster.
Try using them instead. And function calls are not free either.
Xcoor and ycoor are equal, so there is no need to generate them both.

I guess the following would be a lot faster:

def func():
    n = 2000
    a = numarray.zeros((n,n), "Float")
    coor = numarray.arange(0,1,1/float(n))
    
    for i in range(n):
        a[:,i] = numarray.sin(coor*coor[i]) + 8*coor

    print a[1000,1000]
    pass



More information about the Python-list mailing list