【Python】Python のメモリリークに関するあれこれ

■ はじめに

Python で、メモリエラー(MemoryError)に関して
少しずつだが、まとめてみる

目次

【1】メモリリークに関する調査
【2】メモリリークに関する解決案

【1】メモリリークに関する調査

1)tracemalloc
2)memory_profiler
3)objgraph
4)Heapy
5)sys.getsizeof()

etc...
調べれば調べるほど、いっぱいでてくる....

1)tracemalloc

* Python 標準ライブラリ(うれしい)
* From version 3.4

https://docs.python.org/ja/3.6/library/tracemalloc.html
参考文献
https://kazuhira-r.hatenablog.com/entry/2019/04/19/003328

2)memory_profiler

参考文献
https://qiita.com/fockl/items/ada469c138900caaf0a8
https://tech.curama.jp/entry/2018/06/22/120000

3)objgraph

参考文献
https://www.qoosky.io/techs/f0d781cf63

4)Heapy

参考文献
https://qiita.com/yukinoi/items/59d43a3ee207c8aad35b

5)sys.getsizeof()

* Python 標準ライブラリ
* 変数個別で測定する際に使用

https://qiita.com/kpasso1015/items/83062ac14c3c44907e5b

【2】メモリリークに関する解決案

正直、メモリ節約と処理速度は、トレードオフな面もあるから
それぞれの環境で適した方法を取るしかないが、
とりあえず、考えられる項目をあげてみる

1)ファイルをopenする際に with を使う
2)不要なオブジェクトを削除する
3)ファイル読み込みで行ごと処理する
4)Dask を利用する
etc...

ほかの解決案について、以下のサイトを参照のこと。

https://www.haya-programming.com/entry/2017/02/09/190512
https://qiita.com/yukinoi/items/59d43a3ee207c8aad35b
https://www.sejuku.net/blog/74447

1)ファイルをopenする際に with を使う

for i in range(100000000)
  file_path = "hello_world_{}.csv".format
  # ★close忘れ防止になる★
  with open(file_path) as file:
    # 処理

2)不要なオブジェクトを削除する

使用しなくなったオブジェクト(リスト、辞書なども含む)を
del で破棄する

構文

del [オブジェクト名]

3)ファイル読み込みで行ごと処理する

* readline() を利用する
* pandas の場合、chunksize を利用する

readline() を利用する

with open(file_path) as file:
  line = file.readline()
  while line:
    print(line)
    line = file.readline()

pandas の場合、chunksize を利用する

import pandas as pd
 
reader = pd.read_csv('hello_world.csv', encoding='utf-8', chunksize=5)
for line in reader:
    print(line)

4)Dask を利用する

まだ勉強中

https://qiita.com/simonritchie/items/e174f243bc03fb25462e
https://qiita.com/art_526/items/ca003a78535ab4546a01
公式サイト
https://docs.dask.org/en/latest/
サンプル

* CSV に関するサンプルは、以下の関連記事を参照のこと。

https://dk521123.hatenablog.com/entry/2019/11/07/214108

参考文献

https://yakst.com/ja/posts/42

関連記事

Python ~ 基本編 / CSV
https://dk521123.hatenablog.com/entry/2019/11/07/214108
Pandas ~ データ解析支援ライブラリ ~
https://dk521123.hatenablog.com/entry/2019/10/22/014957