6

I have here a recursive function:

def pow(x, n):
    if n == 0:
       return 1
    else:
       return x * pow(x, n-1)
answer = pow(a, b)

And an iterative:

def pow(x, n): # n != 0
    answer = x
    while n > 1:
        answer *= x
        n -= 1
    return answer
answer = pow(a, b)

I'd like to know which one of the them use more memory. I think recursively uses more memory because it keeps 'variables' passed for each function call. If that's right, what would be an formalism to explain this? Is there a nice way to track this memory usage inside code?


I don't think It's a duplicate. The main question isn't about track the memory usage, but It's about the recursive memory usage.

6
  • 2
    Have you tried using a memory profiler? Commented Dec 19, 2014 at 11:14
  • I read about Guppy-PE, but I didn't get very well how to use it. Commented Dec 19, 2014 at 11:16
  • 2
    your iterative solution is incorrect. Commented Dec 19, 2014 at 11:16
  • 1
    thats true! fixing... Commented Dec 19, 2014 at 11:17
  • I'd like to know about the recursive thing too, I don't think its a duplicate. Commented Dec 19, 2014 at 11:19

1 Answer 1

5

No formalism is needed here.

Python stack frames are huge.

Your recursive code is using a lot more memory.

Typical CPython stack frame is over 50 elements plus local variables, taking x86_64 architecture as an example, that's almost 500 bytes.

In [1]: import inspect

In [2]: inspect.stack()[1][0]
Out[2]: <frame at 0x7fed81c86850>

In [3]: inspect.stack()[1][0].__sizeof__()
Out[3]: 472

Good post about frame content: http://tech.blog.aknin.name/2010/07/22/pythons-innards-interpreter-stacks/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.