[Tutor] how to speed up this code?

Pujo Aji ajikoe at gmail.com
Thu Oct 13 09:35:01 CEST 2005


hello chun,
 I use Numeric.
using 'while' instead of for, has the same effect. still slow
 pujo

 On 10/13/05, w chun <wescpy at gmail.com> wrote:
>
> On 10/12/05, Pujo Aji <ajikoe at gmail.com> wrote:
> > I have code like this:
> >
> > def f(x,y):
> > return math.sin(x*y) + 8 * x
> >
> > 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]
> >
> > 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 13x faster...
> >
> > Can anybody help?
> >
> > pujo
>
>
> are zeros() and arange() from NumPy or SciPy? i'll assume so, so
> they're pretty fast already. on 1st glance, i would recommend using a
> while loop instead of range(), which creates a data structure (list of
> 2000 elements) twice:
>
> i = 0
> while i < n:
> j = 0
> while j < n:
> a[i,j] = f(xcoor[i], ycoor[j]) # f(x,y) = sin(x*y) + 8*x
> j += 1
> i += 1
>
> there are probably other improvements that can be made. i also took
> out your 'pass' stmt. :-)
>
> HTH,
> --wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2006,2001
> http://corepython.com
>
> wesley.j.chun :: wescpy-at-gmail.com <http://wescpy-at-gmail.com>
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20051013/eb8f9439/attachment.htm


More information about the Tutor mailing list