我不知道为什么函数f1使用的内存与函数f2相同:
from memory_profiler import memory_usage
class BigObject(object):
def __init__(self):
self.value = "a"*1000000
a = []
def p1(n):
if n == 0:
return
a.append(BigObject())
p1(n-1)
a.pop()
def p2(n, p):
if n == 0:
return
p2(n-1, p + [BigObject()])
def f1():
p1(200)
def f2():
p2(200, [])
mem_usage = memory_usage(f1)
print('Memory usage (in chunks of .1 seconds): %s' % mem_usage)
print('Maximum memory usage of f1: %s' % max(mem_usage))
mem_usage = memory_usage(f2)
print('Memory usage (in chunks of .1 seconds): %s' % mem_usage)
print('Maximum memory usage of f2: %s' % max(mem_usage))
输出:
Memory usage (in chunks of .1 seconds): [28.2421875, 28.55078125, 57.859375, 88.734375, 119.375, 150.7890625, 182.2109375, 213.62890625, 64.45703125, 28.2421875]
Maximum memory usage of f1: 213.62890625
Memory usage (in chunks of .1 seconds): [152.25390625, 152.25390625, 152.25390625, 152.25390625, 152.25390625, 152.25390625, 152.25390625, 177.328125, 209.73046875, 151.296875]
Maximum memory usage of f2: 209.73046875
我的想法是,由于“ +”运算符会在每次函数调用时创建一个新列表,因此p2会不断建立临时列表,因此与p1只能修改一个列表的情况相比,它肯定会使用更多的内存,但这并不是通过观察而诞生。
这是怎么回事?