import sys HAVE_SEND = sys.version_info[:2] >= (2, 5) def simple_gen(runs): for i in xrange(runs): yield i+1 def time_simple_gen(n): 'send just many times' gen = simple_gen(n) gen.send(None) for i in xrange(n-1): x = gen.send(i) assert x==n if not HAVE_SEND: del time_simple_gen def time_simple_gen_iter(n): 'iterate just many times' gen = simple_gen(n) for x in gen: pass assert x==n def time_simple_gen_next(n): 'call next just many times' gen = simple_gen(n) next = gen.next try: while 1: x = next() except StopIteration: pass assert x==n def looping_gen(runs): for i in xrange(runs): # consume a bit of time for x in xrange(1000): y = i + x assert y==i+999 yield i+1 def time_send_loop(n): 'send and loop 1000' gen = looping_gen(n) for i in xrange(n): x = gen.send(None) assert x==n if not HAVE_SEND: del time_send_loop def sub(i): for x in xrange(1000): y = i + x return y def calling_gen(runs): for i in xrange(runs): # take a bit of time y = sub(i) assert y==i+999 yield i+1 def time_send_calling(n): 'send call loop 1000' gen = calling_gen(n) for i in xrange(n): x = gen.send(None) assert x==n if not HAVE_SEND: del time_send_calling