Skip to content

Instantly share code, notes, and snippets.

@gvanrossum
Last active May 29, 2019 10:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gvanrossum/1adb5bee99400ce615a5 to your computer and use it in GitHub Desktop.
Save gvanrossum/1adb5bee99400ce615a5 to your computer and use it in GitHub Desktop.
import sys
import time
sys.setrecursionlimit(1200)
def g1(depth):
if depth > 0:
it = g1(depth-1)
yield next(it)
else:
yield 42
def g2(depth):
if depth > 0:
it = g2(depth-1)
try:
yield next(it)
except StopIteration:
pass
else:
yield 42
def timeit(gen, depth, repeat):
t0 = time.time()
for _ in range(repeat):
assert list(gen(depth)) == [42]
t1 = time.time()
print('%s(%d) * %d: total %.3f, per call %.6f, per frame %.9f' %
(gen.__name__, depth, repeat, t1-t0, (t1-t0)/repeat, (t1-t0)/repeat/depth))
# Note alternating between g1 and g2.
timeit(g1, 1000, 1000)
timeit(g2, 1000, 1000)
timeit(g1, 1000, 1000)
timeit(g2, 1000, 1000)
timeit(g1, 1000, 1000)
timeit(g2, 1000, 1000)
python3.4 genbench.py
g1(1000) * 1000: total 0.660, per call 0.000660, per frame 0.000000660
g2(1000) * 1000: total 0.848, per call 0.000848, per frame 0.000000848
g1(1000) * 1000: total 0.660, per call 0.000660, per frame 0.000000660
g2(1000) * 1000: total 0.865, per call 0.000865, per frame 0.000000865
g1(1000) * 1000: total 0.706, per call 0.000706, per frame 0.000000706
g2(1000) * 1000: total 0.895, per call 0.000895, per frame 0.000000895
python3.5 genbench.py
g1(1000) * 1000: total 0.727, per call 0.000727, per frame 0.000000727
g2(1000) * 1000: total 0.917, per call 0.000917, per frame 0.000000917
g1(1000) * 1000: total 0.730, per call 0.000730, per frame 0.000000730
g2(1000) * 1000: total 0.870, per call 0.000870, per frame 0.000000870
g1(1000) * 1000: total 0.690, per call 0.000690, per frame 0.000000690
g2(1000) * 1000: total 0.908, per call 0.000908, per frame 0.000000908
# This is with Chris A's patch.
./python.exe genbench.py
g1(1000) * 1000: total 0.697, per call 0.000697, per frame 0.000000697
g2(1000) * 1000: total 0.895, per call 0.000895, per frame 0.000000895
g1(1000) * 1000: total 0.685, per call 0.000685, per frame 0.000000685
g2(1000) * 1000: total 0.862, per call 0.000862, per frame 0.000000862
g1(1000) * 1000: total 0.681, per call 0.000681, per frame 0.000000681
g2(1000) * 1000: total 0.898, per call 0.000898, per frame 0.000000898
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment