python - Built-in functions vs recursive functions -


i not mathematician, nor computer scientist - hobbyist programmer , trying teach myself python doing euler project problems. 1 of them requires use of factorial. wrote own calculation using recursive function , realised there built-in function use. having found thought see how quicker recursive function. surprise find slower.

does surprise anyone? curious.

i enclose code (and measure have included loop method comparison).

import math import time  x = 50  def factorial(n):     if n == 0:         return 1     else:         return n * factorial(n-1)  secs = time.clock() print(math.factorial(x)) print ("the built-in function took {a:0.5f} seconds.".format(a = time.clock() - secs))   secs = time.clock() print (factorial(x)) print ("the recursive function took {a:0.5f} seconds.".format(a = time.clock() - secs))  secs = time.clock() factl = 1 in range (1,x+1):     factl *= print (factl) print ("the loop method took {a:0.5f} seconds.".format(a = time.clock() - secs)) 

output:

30414093201713378043612608166064768844377641568960512000000000000

the built-in function took 0.00549 seconds.

30414093201713378043612608166064768844377641568960512000000000000

the recursive function took 0.00299 seconds.

30414093201713378043612608166064768844377641568960512000000000000

the loop method took 0.00259 seconds.

i took code , changed order in 3 methods tested, several times. noticed first method tested takes twice time second one.

i can't explain why, know can't measure function's performance 1 iteration. have repeat function multiple time , compute average time.

ipython comes handy 'magic method' timeit that:

print('math') %timeit math.factorial(x)  print('factorial') %timeit factorial(x)  print('loop') %timeit loopmethod(x) 

output:

math
slowest run took 33.62 times longer fastest. mean intermediate result being cached.
1000000 loops, best of 3: 1.25 µs per loop

factorial
100000 loops, best of 3: 19.4 µs per loop

loop
100000 loops, best of 3: 7.87 µs per loop

the built-in function in average 10 times faster recursive function.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -