memmap (共有メモリ) からの ndarray によってサポートされる比較的大きな Pandas DataFrame が必要です。動作するコード (以下) がありますが、データフレームで計算を実行すると、システム全体の使用率 (トップで測定) が、プロセスがデータをコピーしているかのように上昇します。計算が完了すると、システムのメモリ使用量はベースラインに戻ります。memmap を直接使用して同じ計算を行うと、システムのメモリ使用量は上がりません。この (明らかに) 一時的なメモリ使用量の急増を回避する方法はありますか?
(これらのケースの両方で、top によって報告された個々の python プロセスによって使用されるメモリの割合が上昇することに注意してください、FWIW.)
Pandas 0.20.3、numpy 1.13.1、python 2.7.11 の使用
コード - 最初のスクリプトexample_setup.py
、共有メモリの memmap をセットアップします。
import numpy
N = 7300000000 #this large N makes it really obvious on top what is happening
memmap_file = "/tmp/hello_world.bin"
progress_mod = 10000000
print N/progress_mod
if __name__ == "__main__":
print "opening memmap_file: {}".format(memmap_file)
my_mm = numpy.memmap(memmap_file, dtype="float32", mode="w+", shape=(N,))
print "writing to memmap file integers - N: {}".format(N)
for i in xrange(N):
my_mm[i] = float(i)
if (i%progress_mod) == 0:
print "progress i: {}".format(i)
raw_input("pause here to allow other processes to use shared memory")
2 番目のスクリプトexample_use.py
では、上記の memmap を直接使用し、Pandas DataFrame のバッキングとして使用します。
import example_setup
import numpy
import pandas
if __name__ == "__main__":
memmap_file = example_setup.memmap_file
N = example_setup.N
print "opening memmap_file: {}".format(memmap_file)
my_mm = numpy.memmap(example_setup.memmap_file, dtype="uint32", mode="r", shape=(N,))
print "calculate mean of my_mm, monitor memory using top. This process will show increase usage, but system usage will not increase"
my_mean = my_mm.mean()
print "my_mean: {}".format(my_mean)
raw_input("pause here before doing the above with a dataframe backed by my_mm")
df = pandas.DataFrame(my_mm, copy=False)
print """calculate mean of pandas DataFrame df, monitor memory using top. Both this process and the system usage will increase.
When the calculation finishes, system usage will return to baseline"""
my_df_mean = df.mean()
print "my_df_mean: {}".format(my_df_mean)
raw_input("pause here before exiting")