1. 程式人生 > >得到python物件的真實大小

得到python物件的真實大小

得到python物件的真實大小

sys.getsizeof只給你這個物件和他的屬性的大小,並沒有遞迴的尋找sub-attributes。
sys.getsizeof得到的大小總感覺奇怪…
下面是一個能到真實大小的指令碼:


import sys

def get_size(obj, seen=None):
    """Recursively finds size of objects"""
    size = sys.getsizeof(obj)
    if seen is None:
        seen = set()
    obj_id = id(obj)
    if obj_id in seen:
        return 0
    # Important mark as seen *before* entering recursion to gracefully handle
    # self-referential objects
    seen.add(obj_id)
    if isinstance(obj, dict):
        size += sum([get_size(v, seen) for v in obj.values()])
        size += sum([get_size(k, seen) for k in obj.keys()])
    elif hasattr(obj, '__dict__'):
        size += get_size(obj.__dict__, seen)
    elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
        size += sum([get_size(i, seen) for i in obj])
    return size

例:

class People(object):
    def __init__(self, name, age, dender):
        self.name = name
        self.age = age
        self.gender = gender
        
p1 = People('Li Li', 30, 'Female')
p2 = People('Wang Wang', 25, 'Male')


>>>sys.getsizeof(p1)
>>>56
>>>sys.getsizeof(p2)
>>>56
>>>get_size(p1)
>>>465
>>>get_size(p2)
>>>467

相關介紹:

  1. https://goshippo.com/blog/measure-real-size-any-python-object/
  2. https://github.com/bosswissam/pysize/blob/master/pysize.py