Profiling, recursive func slower than imperative, normal?

S

skanemupp

the 0.409 vs 0.095 is the total times right?
so the imperative function is >4 times faster than the recursive.
or what does tottime stand for?

is this always the case that the recursive function is slower?
the gain is less code?

are some functions only implementable recursively?



def power(nbr, po):
if po==0:
return 1
if po>0:
return nbr*power(nbr, po-1)
if po<0:
return 1/power(nbr, -1*po)

109992 function calls (10002 primitive calls) in 0.409 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall
filename:lineno(function)
1 0.015 0.015 0.409 0.409 <pyshell#217>:1(test1)
1 0.000 0.000 0.409 0.409 <string>:1(<module>)
109989/9999 0.394 0.000 0.394 0.000 myMath.py:39(power)
1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profiler' objects}



def power2(nbr, po):
acc=1
if po >= 1:
acc=nbr
for x in range(1, po):
acc=acc*nbr
if po < 0:
if nbr!=0:
acc=1
for x in range(0, po, -1):
acc=acc/nbr
else:
return "Division by zero"
return acc


20001 function calls in 0.095 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall
filename:lineno(function)
1 0.026 0.026 0.095 0.095 <pyshell#221>:1(test1)
1 0.000 0.000 0.095 0.095 <string>:1(<module>)
9999 0.051 0.000 0.069 0.000 myMath.py:47(power2)
1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profiler' objects}
9999 0.017 0.000 0.017 0.000 {range}
 
T

Terry Reedy

| the 0.409 vs 0.095 is the total times right?
| so the imperative function is >4 times faster than the recursive.
| or what does tottime stand for?
|
| is this always the case that the recursive function is slower?
| the gain is less code?
|
| are some functions only implementable recursively?

Computers can be viewed as linear iteration machines implementing

while True:
execute next instruction and set next pointer appropriately

But algorithms most naturally expressed with multiple recursion usually
look more ungainly when linearized.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top