LoginSignup
71
79

More than 5 years have passed since last update.

Python上でメモリ食っているリスト・配列を探し出す

Last updated at Posted at 2017-07-02

Jupyter(IPython)上でメモリ食っている変数を探し出して削除する - Qiita
に続く、「pythonでのメモリ解放」シリーズ第二弾。

リスト・配列にターゲットを絞って、メモリを圧迫している変数を探し出し、削除する。

コード

以下のような関数を定義しておく。

def print_varsize():
    import types
    print("{}{: >15}{}{: >10}{}".format('|','Variable Name','|','  Size','|'))
    print(" -------------------------- ")
    for k, v in globals().items():
        if hasattr(v, 'size') and not k.startswith('_') and not isinstance(v,types.ModuleType):
            print("{}{: >15}{}{: >10}{}".format('|',k,'|',str(v.size),'|'))
        elif hasattr(v, '__len__') and not k.startswith('_') and not isinstance(v,types.ModuleType):
            print("{}{: >15}{}{: >10}{}".format('|',k,'|',str(len(v)),'|'))

していることは単純で、
「グローバル変数の中で、size属性か__len__属性を持っている変数のみを取り出して、その変数の名前とsizeあるいはlenを出力する」
だけである。
(変数のうち、'_'で始まるものやタイプがmoduleであるものはprint対象から除外している。)

実行結果

>>> import numpy as np
>>> lst = [3,1,4,1,5]
>>> tpl = (1,5,3)
>>> a=np.zeros((100,100,3))
>>> print_varsize()

|  Variable Name|      Size|
 -------------------------- 
|            lst|         5|
|            tpl|         3|
|            Out|         0|
|              a|     30000|
|             In|         8|

このように、サイズの大きいリスト・配列が一目瞭然である。

ここまで出来たらあとは、

del a

のように、いらない変数を指定して削除していったらいい。
メモリを開放して、快適にPython上で操作を継続することが出来る。

71
79
2

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
71
79