[SciPy-user] Python loops too slow

George Nurser gnurser at googlemail.com
Wed Apr 8 08:09:48 EDT 2009


I can see how to do the inner loop of the double loop -- this should
speed it up a lot.
Also where you can, it's probably best to have the second index as the
inner loop, since C and python have the last index as fastest varying
i.e. result[j,i],result[j,i+1] are stored adjacently in memory.

Try replacing

  for i in arange((ngrid / 2)+1):
     for j in arange((ngrid / 2)+1):
        result[j,i] = 2. * pi * sqrt(i ** 2. + j ** 2) / reso / (ngrid*1.0)

by
factor = 2. * pi/(reso *ngrid)
nhalf = ngrid /2+1
ii = arange(nhalf)

for j in arange(nhalf):
      j2 = j**2
      result[j,:nhalf] = factor*sqrt(j2+ii**2)

check this gives the right answer, though!

HTH. George Nurser.

2009/4/8 Ross Williamson <Ross.Williamson at usap.gov>:
> Hi All
>
> I'm trying to convert some IDL code into Python and am coming across the
> incredibly slow for loop issue in python. Now I detest IDL but is there
> any fancy way to make the following code not use for loops? Sorry if
> this is obvious.
>
> def make_ellgrid(ngrid, reso):
>
>   result = zeros([ngrid, ngrid])
>
>   for i in arange((ngrid / 2)+1):
>      for j in arange((ngrid / 2)+1):
>         result[j,i] = 2. * pi * sqrt(i ** 2. + j ** 2) / reso / (ngrid*1.0)
>
>   for i in xrange(ngrid):
>      result[i,ngrid / 2+1:] = result[i,1:(ngrid / 2)][::-1]
>   for i in xrange(ngrid):
>      result[ngrid / 2+1:,i] = result[1:(ngrid / 2),i][::-1]
>
>   return result
>
> Cheers
>
> Ross
>
> _______________________________________________
> SciPy-user mailing list
> SciPy-user at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>



More information about the SciPy-User mailing list