my loop is too slow

Johan Wouters johanw at easics.be
Mon May 10 05:29:26 EDT 1999


SC Zhong wrote:
> 
> 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]
> 
> it took very long time (may be 10 hours in my HP workstation). dimension
> is 142 and a,c,f are all complex.
> 
> I do not want to waste the other part of the program which processing text
> file and rewrite the whole program in C or Fortran.  Is there ways to speed
> the above up?
> 
> Thanks a lot.
> SC CHUNG

One thing would be to predefine the range(dimension) part like:

dim_range
for k in dim_range:
  for i in dim_range:
    for j in dim_range:
      for h in dim_range:
         a[k,i]=a[k,i]+c[k,h]*c[k,j]*f[j,i]*f[i,h]

This will save you about 406*10E6 list creations.

Next thing to notice is the costly lookup of some data items. For instance,
c[k,j], f[j,i], a[k,i] Move these list searches up in the loops like:

dim_range
for k in dim_range:
  for i in dim_range:
    a_ki = a[k,i]
    for j in dim_range:
      c_kj = c[k,j]
      f_ji = f[j,i]
      for h in dim_range:
         a_ki=a_ki+c[k,h]*c_kj*f_ji*f[i,h]
    a[k,i]=a_ki

I hope this gives you an idea on how to further improve code speed (eg. c_kj*f_ji=constant in the h-loop)
Maybe some "map" like construct will give you a faster inner loop

Kind regards,
-- 
===================================================================
Johan Wouters             ===              Easics               ===
ASIC Designer             ===  VHDL-based ASIC design services  ===
Tel: +32-16-395 616          ===================================
Fax: +32-16-395 619      Interleuvenlaan 86, B-3001 Leuven, BELGIUM
mailto:johanw at easics.be           http://www.easics.com




More information about the Python-list mailing list