
On Monday 20 October 2003 07:21 pm, Guido van Rossum wrote: ...
'average' or 'sum'. Whether there is an actual gain in speed depends on how large the list is. You should be able to time examples like
sum([x*x for x in R])
vs.
def gen(R): for x in R: yield x*x sum(gen(R))
for various lengths of R. (The latter would be a good indication of how fast an iterator generator could run.)
with a.py having: def asum(R): sum([ x*x for x in R ]) def gen(R): for x in R: yield x*x def gsum(R, gen=gen): sum(gen(R)) I measure: [alex@lancelot auto]$ timeit.py -c -s'import a' -s'R=range(100)' 'a.asum(R)' 10000 loops, best of 3: 96 usec per loop [alex@lancelot auto]$ timeit.py -c -s'import a' -s'R=range(100)' 'a.gsum(R)' 10000 loops, best of 3: 60 usec per loop [alex@lancelot auto]$ timeit.py -c -s'import a' -s'R=range(1000)' 'a.asum(R)' 1000 loops, best of 3: 930 usec per loop [alex@lancelot auto]$ timeit.py -c -s'import a' -s'R=range(1000)' 'a.gsum(R)' 1000 loops, best of 3: 590 usec per loop [alex@lancelot auto]$ timeit.py -c -s'import a' -s'R=range(10000)' 'a.asum(R)' 100 loops, best of 3: 1.28e+04 usec per loop [alex@lancelot auto]$ timeit.py -c -s'import a' -s'R=range(10000)' 'a.gsum(R)' 100 loops, best of 3: 8.4e+03 usec per loop not sure why gsum's advantage ratio over asum seems to be roughly constant, but, this IS what I measure!-) Alex