codren
codren

Reputation: 11

Why is the memory size different in the function?

While solving the PS problem, there was a problem with memory excess. I looked it up and found one thing

The size of variable 'a' outside the function and the size of variable 'b' within the function were different.

Here is my test code :

from itertools import permutations
import tracemalloc

def test():
    b = list(permutations(range(10)))
    
tracemalloc.start()
test()
a = list(permutations(range(10)))
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')

for stat in top_stats[:10]:
    print(stat)

and the result is :

/Users/codren/Desktop/Coding_Test/test.py:5: size=234 KiB, count=2000, average=120 B
/Users/codren/Desktop/Coding_Test/test.py:9: size=445 MiB, count=3628805, average=129 B

a size is 445 MB,

b size is 234 KB

I think a is more intuitive because the number of permutations is 3628800.

What made the difference? I'd like you to let me know if you know. Thanks :)

Upvotes: 1

Views: 43

Answers (1)

log0
log0

Reputation: 10917

b is thrown away because it is not returned by test().

It does not exist after the test() call.

Upvotes: 1

Related Questions