my loop is too slow

Christian Tismer tismer at appliedbiometrics.com
Mon May 10 13:03:40 EDT 1999


Tim Hochberg wrote:
> 
> 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,:]


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

worked 17 times faster than the iterative complex version, tested
with n=30.
And with n=142, it ran in 444 seconds on a P233 machine.

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaiserin-Augusta-Allee 101   :    *Starship* http://starship.python.net
10553 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home




More information about the Python-list mailing list