10

Python 2.7 では、2.5 GB のテキスト ファイルからすべてのデータをメモリにロードして、次のように処理を高速化します。

>>> f = open('dump.xml','r')
>>> dump = f.read()

次のエラーが発生しました。

Python(62813) malloc: *** mmap(size=140521659486208) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError

Python がバイトデータに140521659486208バイトメモリを割り当てようとしたのはなぜですか? 2563749237すべてのバイトをロードするようにコードを修正するにはどうすればよいですか?

私は約3GBのRAMを無料で持っています。ファイルはウィクショナリーの xml ダンプです。

4

2 に答える 2

13

mmapを使用すると、ファイル全体をすぐにメモリにロードできます。

import mmap

with open('dump.xml', 'rb') as f:
  # Size 0 will read the ENTIRE file into memory!
  m = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) #File is open read-only

  # Proceed with your code here -- note the file is already in memory
  # so "readine" here will be as fast as could be
  data = m.readline()
  while data:
    # Do stuff
    data = m.readline()
于 2012-06-22T15:34:40.383 に答える
-1

Based on some quick googling, I came across this forum post that seems to address the issue that you appear to be having. Assuming that you are running Mac or Linux based on the error code, you may try implementing garbage collection with gc.enable() or gc.collect() as suggested in the forum post.

于 2012-06-22T15:24:10.413 に答える