my loop is too slow

Tim Hochberg hochberg at psn.net
Mon May 10 10:05:16 EDT 1999


SC Zhong wrote in message ...
>
>I tried to learn and use python a week ago, and wrote
>a small application.  When it run the loop:
>
> for k in range(dimension):
> for i in range(dimension):
> for j in range(dimension):
> for h in range(dimension):
> a[k,i]=a[k,i]+c[k,h]*c[k,j]*\
> f[j,i]*f[i,h]


Are you using Numeric Python? The array notation ([x,y]) would indicate that
you are either using Numeric or your are using dictionaries to represent
arrays. If you are doing the second, it is likely to be quite slow.

If you are using or can use Numeric, something like the following (untested)
code should speed things up significantly.

from Numeric import *
dimRange = range(dimension)
# Make sure a is an array.
a = asarray(a)
for j in dimRange:
    for h in dimRange:
        a = a + (c[:,h]*c[:,j])[:,NewAxis] * (f[j,:]*f[:,h])[NewAxis,:]








More information about the Python-list mailing list