3

を使用して大きな h5 ファイルをメモリにロードしていますnumpy ndarray。私のシステム(Win 7教授、6 GB RAM)は、python.exeが約2 GBの物理メモリを使用できるようになっていると読みました。

しかし、私はMemoryErrorすでに1 GBの恥ずかしがり屋になっています。さらに奇妙なことに、この下限はnumpy array's にのみ適用され、 a には適用されないようlistです。

ここにある次の関数を使用して、メモリ消費量をテストしました。

import psutil
import gc
import os
import numpy as np
from matplotlib.pyplot import pause

def memory_usage_psutil():
    # return the memory usage in MB
    process = psutil.Process(os.getpid())
    mem = process.get_memory_info()[0]/float(2**20)
    return mem

テスト 1:通常のリストのメモリ制限をテストする

print 'Memory - %d MB' %memory_usage_psutil() # prints memory usage after imports
a = []
while 1:
    try:
        a.append([x*2000 for x in xrange(10000)])
    except MemoryError:
        print 'Memory - %d MB' %memory_usage_psutil()
        a = []
        print 'Memory - %d MB' %memory_usage_psutil()
        print 'run garbage collector: collected %d objects.' %gc.collect()
        print 'Memory - %d MB\n\n' %memory_usage_psutil()
        break

テスト 1 の印刷物:

Memory - 39 MB
Memory - 1947 MB
Memory - 1516 MB
run garbage collector: collected 0 objects.
Memory - 49 MB

テスト 2:多数の大きな を作成np.arrayする

shape = (5500,5500)
names = ['b', 'c', 'd', 'g', 'h']

try:
    for n in names:
        globals()[n] = np.ones(shape, dtype='float64')
        print 'created variable %s with %0.2f MB'\
        %(n,(globals()[n].nbytes/2.**20))
except MemoryError:
    print 'MemoryError, Memory - %d MB. Deleting files..'\
    %memory_usage_psutil()
    pause(2)
    # Just added the pause here to be able to observe
    # the spike of memory in the Windows task manager.
    for n in names:
        globals()[n] = []
    print 'Memory - %d MB' %memory_usage_psutil()
    print 'run garbage collector: collected %d objects.' %gc.collect()
    print 'Memory - %d MB' %memory_usage_psutil()

テスト 2 印刷:

Memory - 39 MB
created variable b with 230.79 MB
created variable c with 230.79 MB
created variable d with 230.79 MB
created variable g with 230.79 MB
MemoryError, Memory - 964 MB. Deleting files..
Memory - 39 MB
run garbage collector: collected 0 objects.
Memory - 39 MB

私の質問: 2 GB の制限に近づく前に を取得するのはなぜですか? また、とそれぞれMemoryErrorのメモリ制限に違いがあるのはなぜですか? または何が欠けているのでしょうか? 私はpython 2.7とnumpy 1.7.1を使用していますlistnp.array

4

1 に答える 1

2

これはおそらく、numpy 配列が (速度のために) C 配列ライブラリを使用しており、それが malloc を呼び出しているために発生している可能性があります。連続する1GB のメモリを割り当てることができないため、これは失敗します。さらに、Python リストはリンクされたリストとして実装されているため、リストに必要なメモリは連続している必要はないと推測しています。したがって、使用可能なメモリが十分にあるのに断片化されている場合、配列の malloc は失敗しますが、リンクされたリストを使用すると、連続していないすべての部分を使用できます。

于 2013-10-04T00:25:10.133 に答える