LoginSignup
13
11

More than 5 years have passed since last update.

オブジェクトの総メモリ使用量をざっくり見積もる

Last updated at Posted at 2016-01-14

環境: Python 3.5.0, 64bit

オブジェクトのメモリ使用量はsys.getsizeofで調べられますが、参照先のオブジェクトの分まではカウントされません。

>>> import sys
>>> sys.getsizeof([1, 2 ,3])
88
>>> sys.getsizeof([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
88

コンテナの中の要素も含めておおよその総メモリ使用量が知りたい場合は、参照先のオブジェクトを全て辿ってgetsizeofの値を積算する必要があるようです。

参考:
http://code.activestate.com/recipes/577504/

total_size.py

import sys

from itertools import chain
from collections import deque


def total_size(obj, verbose=False):
    seen = set()

    def sizeof(o):
        if id(o) in seen:
            return 0
        seen.add(id(o))
        s = sys.getsizeof(o, default=0)
        if verbose:
            print(s, type(o), repr(o))
        if isinstance(o, (tuple, list, set, frozenset, deque)):
            s += sum(map(sizeof, iter(o)))
        elif isinstance(o, dict):
            s += sum(map(sizeof, chain.from_iterable(o.items())))
        elif "__dict__" in dir(o):  # もっと良い方法はあるはず
            s += sum(map(sizeof, chain.from_iterable(o.__dict__.items())))
        return s

    return sizeof(obj)

他にもpickleを利用する方法などがあるようです。

13
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11