List comprehensions performance

Bengt Richter bokr at oz.net
Thu Sep 30 23:22:49 CEST 2004


On Thu, 30 Sep 2004 20:13:04 +0200, aleaxit at yahoo.com (Alex Martelli) wrote:

>Bengt Richter <bokr at oz.net> wrote:
>   ...
>> >...but if the for loop is NOT equivalent (it doesn't accumulate results
>> >into a resulting list), it's still faster.  As I posted:
>> >
>> >kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' 'for x in
>> >xrange(999): f()'
>> >1000 loops, best of 3: 1.29e+03 usec per loop
>> >kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' '[f() for x in
>> >xrange(999)]'
>> >1000 loops, best of 3: 1.45e+03 usec per loop
>> >
>> >the LC is paying for the building of a list of 999 references to None,
>> >which the for loop easily avoids, so the for loop is much faster here.
>> 
>> What if you abuse the LC so it makes an empty list? E.g.,
>>     [None for x in xrange(999) if f() and False]
>
>Now tell me, is timing so HARD...?!  This obfuscation times (on 2.4 and
>the same old iBook as above) to 1.38e+03 usec per loop, still slower
>than the plain old loop -- the if/and rigmarole costs...
>
Sure, I was just wondering what would happen if you traded that for list growth overhead.
Anyway, thanks. It _is_ hard to compare with someone else's previous timing numbers ;-)
Maybe timeit.py should have an option for bogomips normalization or returning
time*bogomips. My system needs an upgrade ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list