Skip to content

Instantly share code, notes, and snippets.

@toshok
Created April 27, 2015 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toshok/603427ed27ec28151f51 to your computer and use it in GitHub Desktop.
Save toshok/603427ed27ec28151f51 to your computer and use it in GitHub Desktop.
import time
def get_sources():
for i in xrange(100000):
yield i
class get_sources2(object):
def __init__(self):
self.range_iter = xrange(100000).__iter__()
def __iter__(self):
return self
def __hasnext__(self):
return self.range_iter.__hasnext__()
def next(self):
return self.range_iter.next()
def test_impl(impl, msg):
low_watermark = 100000
iter_count = 0
for s in xrange(100000):
start = time.time()
sum = 0
for i in impl():
sum = sum + i
elapsed = time.time() - start
if elapsed < low_watermark:
iter_count = 0
low_watermark = elapsed
iter_count = iter_count + 1
if iter_count == 100:
print "%s: %4.1fus" % (msg, elapsed * 1000000.0,)
return
test_impl(get_sources, "for-yield loop")
test_impl(get_sources2, "iterable class with __hasnext__")
# python output:
# for-yield loop: 5727.1us
# iterable class with __hasnext__: 21207.1us
# pyston_release output
# for-yield loop: 16795.2us
# iterable class with __hasnext__: 9035.8us
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment