小编Amm*_*ser的帖子

装饰器消耗更多内存吗?

在 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)

python memory decorator

3
推荐指数
1
解决办法
117
查看次数

标签 统计

decorator ×1

memory ×1

python ×1