Skip to content

Instantly share code, notes, and snippets.

@aliles
Created July 7, 2011 12:10
Show Gist options
  • Save aliles/1069380 to your computer and use it in GitHub Desktop.
Save aliles/1069380 to your computer and use it in GitHub Desktop.
Benchmark a tail call optimisation decorator.
[aliles@macbookpro ~]$ time python2.7 timeit_tco.py 40000
Computed number of length 166714
1.014175 seconds on CPU
real 0m2.109s
user 0m2.094s
sys 0m0.013s
[aliles@macbookpro ~]$ time pypy timeit_tco.py 40000
Computed number of length 166714
3.392062 seconds on CPU
real 0m8.614s
user 0m8.521s
sys 0m0.082s
import sys
import time
class tail_recursive(object):
"""Tail recursion decorator by George Sakkis
http://code.activestate.com/recipes/496691-new-tail-recursion-decorator/#c3
"""
def __init__(self, func):
self.func = func
self.firstcall = True
self.CONTINUE = object()
def __call__(self, *args, **kwd):
if self.firstcall:
func = self.func
CONTINUE = self.CONTINUE
self.firstcall = False
try:
while True:
result = func(*args, **kwd)
if result is CONTINUE: # update arguments
args, kwd = self.argskwd
else: # last call
return result
finally:
self.firstcall = True
else: # return the arguments of the tail call
self.argskwd = args, kwd
return self.CONTINUE
@tail_recursive
def factorial(n, acc=1):
"calculate a factorial"
if n == 0:
return acc
res = factorial(n-1, n*acc)
return res
if __name__ == '__main__':
depth = int(sys.argv[1])
start = time.clock()
value = factorial(depth)
stop = time.clock()
print 'Computed number of length %d' % len(str(value))
print stop - start, 'seconds on CPU'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment