Code speedup tips

Alex Martelli aleax at aleax.it
Sun Mar 9 12:48:28 EST 2003


Frank Buss wrote:

>> But I think for the calculation of the sum of all 1's, it could be
>> faster. Currently it is implemented like this:
>> 
>> # print the number of '1's for all automaton steps
>> for step in range(length / 2):
>>   print reduce(lambda x, y: x+y, rule30.current)
>>   rule30.step()
>> 
>> Where 'current' is a Numeric's array. Any tips?
> 
> Changjune Kim sent me the idea, to use ".count(1)". This doesn't work with
> the Numeric array (perhaps it should be added to the Numeric array-class),
> but after ".tolist()" it is 5 times faster: 11 seconds for 5000 arrays of
> size 10000 with tolist().count(1) and 52 seconds for my lambda construct.
> 
> for step in range(length / 2):
>   print(rule30.current.tolist().count(1))
>   rule30.step()

My machine and yours seem to have similar speed -- for 5000
arrays of 10000 ones each:

47.10 lambdareduce
30.85 addreduce
11.32 count1s
0.33 sum

the last line is simply calling Numeric.sum(rule30.current)
and is of course the speediest solution.  addreduce uses
operator.add instead of your lambda, by the way.


Alex





More information about the Python-list mailing list