Why generators take long time?

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Jan 19 05:24:03 EST 2016


On 19 Jan 2016 10:16, "Steven D'Aprano" <steve at pearwood.info> wrote:
>
> [steve at ando ~]$ python -m timeit -s "from collections import deque"
>     -s "it = iter([i for i in xrange(1000)])" "deque(it, maxlen=0)"
> 1000000 loops, best of 3: 0.913 usec per loop
>
>
> [steve at ando ~]$ python -m timeit -s "from collections import deque"
>     -s "it = (i for i in xrange(1000))" "deque(it, maxlen=0)"
> 1000000 loops, best of 3: 0.965 usec per loop

Surely the iterator in the above benchmarks is consumed during the first of
1000000 loops. Subsequent loops are just calling next on an exhausted
iterator.

--
Oscar



More information about the Python-list mailing list