genexp performance problem?

Delaney, Timothy (Tim) tdelaney at avaya.com
Wed May 31 02:58:21 CEST 2006


Giovanni Bajo wrote:

> python -mtimeit "sum(int(L) for L in xrange(3000))"
> 100 loops, best of 3: 5.04 msec per loop
> 
> python -mtimeit "import itertools; sum(itertools.imap(int,
> xrange(3000)))" 100 loops, best of 3: 3.6 msec per loop
> 
> I thought the two constructs could achieve the same speed.

What does it give you with:

python -mtimeit -s "g = (int(L) for L in xrange(3000))" "sum(g)"

?

I get:

python -mtimeit "import itertools; sum(itertools.imap(int,
xrange(3000)))"
100 loops, best of 3: 3.99 msec per loop

python -mtimeit -s "import itertools" "sum(itertools.imap(int,
xrange(3000)))"
100 loops, best of 3: 3.97 msec per loop

python -mtimeit "sum(int(L) for L in xrange(3000))"
100 loops, best of 3: 6.76 msec per loop

python -mtimeit -s "g = (int(L) for L in xrange(3000))" "sum(g)"
1000000 loops, best of 3: 1.09 usec per loop

The generator comprehension needs to create a new generator each time
around.

Tim Delaney



More information about the Python-list mailing list