camabeh
3/3/2017 - 7:37 PM

Benchmark

Benchmark

from timeit import timeit

setup_chunks_iter = '''
def chunks_iter(n, seq):
    """Chunks from iterable"""

    for i in range(0, len(seq), n):
        yield seq[i:i + n]
'''
setup_chunks_gen = '''
from itertools import chain, islice

def chunks_gen(size, iterable):
    """Chunks from generator"""
    iterator = iter(iterable)
    for first in iterator:
        yield chain([first], islice(iterator, size - 1))
'''

# Cpython 3.6: 13.824648286914453
# PyPy 5.5.0: 8.559067378053442
print(timeit('list(chunks_iter(2, list(range(10**6))))', setup=setup_chunks_iter, number=100))

# Cpython 35.51819608104415
# PyPy 5.5.0: 26.60674525098875
print(timeit('list(map(list, chunks_gen(2, list(range(10**6)))))', setup=setup_chunks_gen, number=100))