I would like to develop a Python decorator that tells me the real memory size of the objects in a Python function.
from pympler import asizeof
import functools
def get_size(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
func(*args, **kwargs)
print(f"Memory allocation (KB) of variables of the function {func.__name__!r}")
for key in locals().keys():
print(f"size of object {key} is {asizeof.asizeof(key)/10**3}")
return wrapper
@get_size
def my_function():
nums = [1,2,3,4,5]
more_nums = [nums, nums, nums, nums, nums]
my_function()
The current output is not what I am looking for, as it takes the function as the only object, not the objects in contains inside (nums, more_nums
) which are the ones of interest to me.
Memory allocation (KB) of variables of the function 'my_function'
size of object args is 0.056
size of object kwargs is 0.056
size of object func is 0.056