Why generators take long time?

Steven D'Aprano steve at pearwood.info
Tue Jan 19 18:58:43 EST 2016


On Tue, 19 Jan 2016 09:24 pm, Oscar Benjamin wrote:

> 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.

You know, I think you're right. Damn.

I keep getting bitten by that aspects of iterators and timeit.



-- 
Steven




More information about the Python-list mailing list