Python Forum
Why recursive function consumes more of processing time than loops?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why recursive function consumes more of processing time than loops?
#7
Starting with a really simple case:
fib[4] = fib[3] + fib[2]
fib[4] = (fib[3] = fib[2] + fib[1]) + (fib[2] = fib[1] + fib[0])
fib[4] = (fib[3] = (fib[2] = fib[1] + fib[0]) + fib[1]) + (fib[2] = fib[1] + fib[0])
That's 9 calls to fib().

This code records the number of times fib[n] is called for each value of n:
calls = {}

def fib(n):
    calls[n] = calls.get(n, 0) + 1
    if n < 2:
        return 1
    else:
        return fib(n-1) + fib(n-2)
fib(5)
for n, count in calls.items():
    print(f'{n:3d} : {count:5d}')
print('Total', sum(calls.values()))
Output:
5 : 1 4 : 1 3 : 2 2 : 3 1 : 5 0 : 3 Total 15
Just doubling starting n from 5 to 10 does this:
Output:
10 : 1 9 : 1 8 : 2 7 : 3 6 : 5 5 : 8 4 : 13 3 : 21 2 : 34 1 : 55 0 : 34 Total 177
And this is the horrible thing that happens when n = 40
Output:
40 : 1 39 : 1 38 : 2 37 : 3 36 : 5 35 : 8 34 : 13 33 : 21 32 : 34 31 : 55 30 : 89 29 : 144 28 : 233 27 : 377 26 : 610 25 : 987 24 : 1597 23 : 2584 22 : 4181 21 : 6765 20 : 10946 19 : 17711 18 : 28657 17 : 46368 16 : 75025 15 : 121393 14 : 196418 13 : 317811 12 : 514229 11 : 832040 10 : 1346269 9 : 2178309 8 : 3524578 7 : 5702887 6 : 9227465 5 : 14930352 4 : 24157817 3 : 39088169 2 : 63245986 1 : 102334155 0 : 63245986 Total 331160281
ibreeden and M83Linux like this post
Reply


Messages In This Thread
RE: Why recursive function consumes more of processing time than loops? - by deanhystad - May-17-2021, 06:29 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  return next item each time a function is executed User3000 19 2,353 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  with open context inside of a recursive function billykid999 1 594 May-23-2023, 02:37 AM
Last Post: deanhystad
  time function does not work tester_V 4 3,079 Oct-17-2021, 05:48 PM
Last Post: tester_V
  Real Time Audio Processing with Python Sound-Device not working Slartybartfast 2 4,030 Mar-14-2021, 07:20 PM
Last Post: Slartybartfast
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,472 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  Can you end the Time.sleep function boier96 9 9,561 Jan-16-2021, 10:09 PM
Last Post: Serafim
  Real Time signal processing tagalog 2 2,696 Dec-12-2020, 05:23 AM
Last Post: tagalog
  Execution of Another Recursive Function muzikman 5 3,043 Dec-04-2020, 08:13 PM
Last Post: snippsat
  Don't Understand Recursive Function muzikman 9 3,748 Dec-03-2020, 05:10 PM
Last Post: muzikman
  list call problem in generator function using iteration and recursive calls postta 1 1,936 Oct-24-2020, 09:33 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020