Created
July 8, 2012 17:19
-
-
Save kojiromike/3071880 to your computer and use it in GitHub Desktop.
Compare implementations of islice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from timeit import timeit | |
setup = ''' | |
l = range(20) | |
def islice(iterable, *args): | |
# islice('ABCDEFG', 2) --> A B | |
# islice('ABCDEFG', 2, 4) --> C D | |
# islice('ABCDEFG', 2, None) --> C D E F G | |
# islice('ABCDEFG', 0, None, 2) --> A C E G | |
s = slice(*args) | |
it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1)) | |
nexti = next(it) | |
for i, element in enumerate(iterable): | |
if i == nexti: | |
yield element | |
nexti = next(it) | |
qslice = (x for x, idx in zip(l, range(0, len(l))) if 10 <= idx < 15) | |
rslice = (x for idx, x in enumerate(l) if 10 <= idx < 15) | |
''' | |
exec(setup) | |
list_islice = list(islice(l, 10, 15)) | |
list_qslice = list(qslice) | |
list_rslice = list(rslice) | |
assert list_islice == list_qslice, (list_islice, list_qslice) | |
assert list_islice == list_rslice, (list_islice, list_rslice) | |
assert list_rslice == list_qslice, (list_rslice, list_qslice) | |
print '1M iterations of islice(l, 10, 15): %f' % timeit('islice(l, 10, 15)', setup, number=10**6) | |
print '1M iterations of (x for x, idx in zip(l, range(0, len(l))) if 10 <= idx < 15): %f' % timeit('(x for x, idx in zip(l, range(0, len(l))) if 10 <= idx < 15)', setup, number=10**6) | |
print '1M iterations of (x for idx, x in enumerate(l) if 10 <= idx < 15): %f' % timeit('(x for idx, x in enumerate(l) if 10 <= idx < 15)', setup, number=10**6) | |
print '1M iterations of list(islice(l, 10, 15)): %f' % timeit('list(islice(l, 10, 15))', setup, number=10**6) | |
print '1M iterations of list((x for x, idx in zip(l, range(0, len(l))) if 10 <= idx < 15)): %f' % timeit('list((x for x, idx in zip(l, range(0, len(l))) if 10 <= idx < 15))', setup, number=10**6) | |
print '1M iterations of list((x for idx, x in enumerate(l) if 10 <= idx < 15)): %f' % timeit('list((x for idx, x in enumerate(l) if 10 <= idx < 15))', setup, number=10**6) | |
# 1M iterations of islice(l, 10, 15): 0.629101 | |
# 1M iterations of (x for x, idx in zip(l, range(0, len(l))) if 10 <= idx < 15): 3.772903 | |
# 1M iterations of (x for idx, x in enumerate(l) if 10 <= idx < 15): 1.280824 | |
# 1M iterations of list(islice(l, 10, 15)): 7.466557 | |
# 1M iterations of list((x for x, idx in zip(l, range(0, len(l))) if 10 <= idx < 15)): 8.542739 | |
# 1M iterations of list((x for idx, x in enumerate(l) if 10 <= idx < 15)): 6.021005 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment