在 Corey Schafer 教程中,他编写了以下代码来测量特定函数消耗的内存量。
import time
import random
import memory_profiler
names = ['john', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Art', 'Business']
print('Memory (before): {}Mb'.format(memory_profiler.memory_usage()))
def people_list(num_of_people):
result = []
for i in range(num_of_people):
person = {'id': i,
'name' : random.choice(names),
'major' : random.choice(majors)}
result.append(person)
return result
t1 = time.process_time()
people_list(1000000)
t2 = time.process_time()
print('Memory (After): {}Mb'.format(memory_profiler.memory_usage()))
print('Took {} seconds'.format(t2-t1))
Run Code Online (Sandbox Code Playgroud)
结果是
Memory (before): [34.21875]Mb
Memory (After): [34.47265625]Mb
Took 2.390625 seconds
Run Code Online (Sandbox Code Playgroud)
但是当我尝试创建一个装饰器来为我的函数添加内存和时间测量功能时,函数执行前后的内存差异是巨大的。这是我的代码
import time
import random
import memory_profiler …Run Code Online (Sandbox Code Playgroud)