python - 装饰器会消耗更多内存吗?

标签 python memory decorator

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

结果是

Memory (before): [34.21875]Mb
Memory (After): [34.47265625]Mb
Took 2.390625 seconds

但是当我尝试创建一个装饰器以将内存和时间测量功能添加到我的函数中时,函数执行前后的内存差异非常大。 这是我的代码

import time
import random
import memory_profiler

names = ['john', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Art', 'Business']

def decorator(original_func):
    def wrapper(*args, **kwargs):
        before_memory = memory_profiler.memory_usage()
        print('Memory (before): {} Mbs'.format(before_memory))
        t1 = time.time()
        output = original_func(*args, **kwargs)
        t2 = time.time()
        time_diff = t2 - t1
        after_memory = memory_profiler.memory_usage()
        print("Memory (after): {} Mbs".format(after_memory))
        print('{} ran in {} seonds'.format(original_func.__name__, time_diff))
        return output
    return wrapper

@decorator
def people_list(num):
    result = []
    for i in range(num):
        person = {'id' : i+1, 
                  'name' : random.choice(names), 
                  'major' : random.choice(majors)}
        result.append(person)
    return result

people_list(1000000)

结果是

Memory (before): [47.07421875] Mbs
Memory (after): [319.875] Mbs
people_list ran in 2.5296807289123535 seonds

最佳答案

如果没有装饰器,您将立即丢弃函数调用的结果。在装饰器示例中,在查看内存使用情况时,结果保存在输出中。

尝试第一个示例:

t1 = time.process_time()
output = people_list(1000000)
t2 = time.process_time()
print('Memory (After): {}Mb'.format(memory_profiler.memory_usage()))
print('Took {} seconds'.format(t2-t1))

并且您应该获得相同的内存使用量。

关于python - 装饰器会消耗更多内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59491221/

相关文章:

Python装饰器函数执行

JavaScript: TypeError: work.calls is not iterable in function decorator(初学者问题)

c# - Autofac 修饰使用程序集扫描注册的开放泛型

python - 装饰Flask MethodView派生类中的方法

Python:将上下文(contextvars.Context)复制到单独的线程

C# WinForm 内存泄漏

.net - 确定一个类使用多少内存?

python - 键盘中断和 os.system 与 subprocess.call

python - 如何在python中向mongoDB添加数据

java - 为什么 DoubleBuffer.put() 分配内存,我应该如何避免这种情况发生?