getrecursiondepth

Andrew Dalke adalke at mindspring.com
Fri Oct 1 17:03:51 CEST 2004


Manlio Perillo wrote:
>>>>def foo2(n = 0):
> 
>        if pystate.firstlevel_call():
> 	   foo2.recursiondepth = 0
>        else:
>            foo2.recursiondepth += 1
> 	    
>        #print 'n = %s, recursion depth = %s' % (n,
> foo2.recursiondepth)
>        if n == 5: return
>        foo2(n + 1)

In addition, if you aren't supporting threads
then the following will also work.

def foo3(n=0):
   foo3.recursiondepth += 1
   try:
     if n == 5: return
     foo3(n+1)
   finally:
     foo3.recursiondepth -= 1

foo3.recursiondepth = 0

% timeit.py -s "import spam" "spam.foo2()"
10000 loops, best of 3: 70.8 usec per loop
% timit.py -s "import spam" "spam.foo3()"
10000 loops, best of 3: 47.6 usec per loop

Still, the fastest solution, which is also
concise, thread-safe and portable (meaning
that can be easily translated to other
languages) is

def _foo4(n, depthlimit):
     if depthlimit == 0: return
     _foo4(n+1, depthlimit-1)

def foo4(n=0):
     _foo4(n, 5)


% timeit.py -s "import spam" "spam.foo4()"
100000 loops, best of 3: 16.4 usec per loop


				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list