profile.py 文件源码

python
阅读 26 收藏 0 点赞 0 评论 0

项目:fg21sim 作者: liweitianux 项目源码 文件源码
def getsize(obj):
    """
    Recursively iterate to sum size of object & members.

    Returns
    -------
    size : int
        The size of the object in units of "Bytes".

    Credit
    ------
    * How do I determine the size of an object in Python?
      https://stackoverflow.com/a/30316760/4856091
    """
    zero_depth_bases = (str, bytes, Number, range, bytearray)

    def inner(obj, _seen_ids=set()):
        obj_id = id(obj)
        if obj_id in _seen_ids:
            return 0

        _seen_ids.add(obj_id)
        size = sys.getsizeof(obj)
        if isinstance(obj, zero_depth_bases):
            # bypass remaining control flow and return
            pass
        elif isinstance(obj, (tuple, list, Set, deque)):
            size += sum(inner(i) for i in obj)
        elif isinstance(obj, Mapping) or hasattr(obj, "items"):
            size += sum(inner(k) + inner(v) for k, v in obj.items())
        # Check for custom object instances - may subclass above too
        if hasattr(obj, "__dict__"):
            size += inner(vars(obj))
        if hasattr(obj, "__slots__"):
            # can have ``__slots__`` with ``__dict__``
            size += sum(inner(getattr(obj, s))
                        for s in obj.__slots__ if hasattr(obj, s))
        return size

    return inner(obj)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号