Improve the performance of a loop

Steven Bethard steven.bethard at gmail.com
Wed May 25 19:27:45 EDT 2005


querypk at gmail.com wrote:
> vbox = array(m) (size: 1000x1000 approx)
> for b in bx:
>     vbox[ b[1], b[0]:b[2] ] = 0
>     vbox[ b[3], b[0]:b[2] ] = 0
>     vbox[ b[1]:b[3], b[0] ] = 0
>     vbox[ b[1]:b[3], b[2] ] = 0

This may not help, but you could try to minimize the number of times you 
call b's __getitem__, e.g.:

for b0, b1, b2, b3 in bx:
     vbox[b1, b0:b2] = 0
     vbox[b3, b0:b2] = 0
     vbox[b1:b3, b0] = 0
     vbox[b1:b3, b2] = 0

If it helps, I wouldn't expect it to help a lot though.  You could also try:

for b0, b1, b2, b3 in bx:
     b0_2 = slice(b0, b2)
     b1_3 = slice(b1, b3)
     vbox[b1, b0_2] = 0
     vbox[b3, b0_2] = 0
     vbox[b1_3, b0] = 0
     vbox[b1_3, b2] = 0

But again, I wouldn't expect dramatic improvements...

STeVe



More information about the Python-list mailing list