Skip to content

Instantly share code, notes, and snippets.

@TonyDiana
Last active June 12, 2021 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TonyDiana/9fcbef68f413144fe3055195c629aea7 to your computer and use it in GitHub Desktop.
Save TonyDiana/9fcbef68f413144fe3055195c629aea7 to your computer and use it in GitHub Desktop.
Medir la memoria consumida por un objeto Python
# -*- coding: utf-8 *-*
"""
:Propósito: Medir la memoria consumida por un objeto Python
:Autor: https://goshippo.com/blog/measure-real-size-any-python-object/
:Versión: Desconocido
:Adaptación: Tony Diana
Se ha mejorado y se añadió medir también los atributos de los objetos
---------------------------------------------------------------------------
"""
import sys
def get_size(obj, almacen=None):
""" Medir recursivamente la ocupación en memoria de un objeto Python. """
size = sys.getsizeof(obj)
# --- Establecer el almacén de datos
if almacen is None:
almacen = set()
# --- Consultar si el objeto ya se encuentra en el almacén, para no sumarlo
obj_id = id(obj)
if obj_id in almacen:
return 0
# Añadir el ID del objeto al almacén. Según el autor original, una manera
# muy elegante de manejar la recursividad, y lo cierto es que sí lo es
almacen.add(obj_id)
# --- Consultar el tamaño de ese elemento, según su tipo
if isinstance(obj, dict):
size += sum([get_size(v, almacen) for v in obj.values()])
size += sum([get_size(k, almacen) for k in obj.keys()])
elif isinstance(obj, object):
size += sum([get_size(v, almacen) for v in dir(obj)])
elif hasattr(obj, '__dict__'):
size += get_size(obj.__dict__, almacen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_size(i, almacen) for i in obj])
return size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment