41

iPython を使用してコードを実行しています。オブジェクトのメモリ使用量を確認できるモジュールまたはコマンドがあるかどうか疑問に思います。例えば:

In [1]: a = range(10000)
In [2]: %memusage a
Out[2]: 1MB

のようなもの%memusage <object>で、オブジェクトが使用するメモリを返します。

複製

Python でオブジェクトが使用しているメモリ量を調べる

4

4 に答える 4

23

numpy配列を使用している場合は、属性を使用しndarray.nbytesてメモリ内のサイズを評価できます。

from pylab import *   
d = array([2,3,4,5])   
d.nbytes
#Output: 32
于 2013-03-23T19:30:46.750 に答える
14

更新: Pythonオブジェクトのサイズを見積もるための別の、おそらくより徹底的なレシピがあります。

これは同様の質問に対処する スレッドです

提案された解決策は、プリミティブの既知のサイズ、Pythonのオブジェクトのオーバーヘッド、および組み込みのコンテナータイプのサイズの推定値を使用して、独自のソリューションを作成することです。

コードはそれほど長くないので、ここに直接コピーします。

def sizeof(obj):
    """APPROXIMATE memory taken by some Python objects in 
    the current 32-bit CPython implementation.

    Excludes the space used by items in containers; does not
    take into account overhead of memory allocation from the
    operating system, or over-allocation by lists and dicts.
    """
    T = type(obj)
    if T is int:
        kind = "fixed"
        container = False
        size = 4
    elif T is list or T is tuple:
        kind = "variable"
        container = True
        size = 4*len(obj)
    elif T is dict:
        kind = "variable"
        container = True
        size = 144
        if len(obj) > 8:
            size += 12*(len(obj)-8)
    elif T is str:
        kind = "variable"
        container = False
        size = len(obj) + 1
    else:
        raise TypeError("don't know about this kind of object")
    if kind == "fixed":
        overhead = 8
    else: # "variable"
        overhead = 12
    if container:
        garbage_collector = 8
    else:
        garbage_collector = 0
    malloc = 8 # in most cases
    size = size + overhead + garbage_collector + malloc
    # Round to nearest multiple of 8 bytes
    x = size % 8
    if x != 0:
        size += 8-x
        size = (size + 8)
    return size
于 2009-02-19T04:07:23.133 に答える