1GB RAM を搭載した Mac Mini で Python 2.6 を使用しています。巨大なテキストファイルを読み込みたい
$ ls -l links.csv; file links.csv; tail links.csv
-rw-r--r-- 1 user user 469904280 30 Nov 22:42 links.csv
links.csv: ASCII text, with CRLF line terminators
4757187,59883
4757187,99822
4757187,66546
4757187,638452
4757187,4627959
4757187,312826
4757187,6143
4757187,6141
4757187,3081726
4757187,58197
したがって、ファイルの各行は、コンマで区切られた 2 つの整数値のタプルで構成されます。ファイル全体を読み込んで、2 番目の列に従って並べ替えたいと思います。ファイル全体をメモリに読み込まずに並べ替えを実行できることはわかっています。しかし、500MB のファイルの場合、1GB が利用可能であるため、メモリ内で実行できるはずだと考えました。
ただし、ファイルを読み込もうとすると、Python はディスク上のファイルが必要とするよりも多くのメモリを割り当てているようです。そのため、1 GB の RAM を使用しても、500 MB のファイルをメモリに読み込むことができません。ファイルを読み取り、メモリ消費に関する情報を出力するための私の Python コードは次のとおりです。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
infile=open("links.csv", "r")
edges=[]
count=0
#count the total number of lines in the file
for line in infile:
count=count+1
total=count
print "Total number of lines: ",total
infile.seek(0)
count=0
for line in infile:
edge=tuple(map(int,line.strip().split(",")))
edges.append(edge)
count=count+1
# for every million lines print memory consumption
if count%1000000==0:
print "Position: ", edge
print "Read ",float(count)/float(total)*100,"%."
mem=sys.getsizeof(edges)
for edge in edges:
mem=mem+sys.getsizeof(edge)
for node in edge:
mem=mem+sys.getsizeof(node)
print "Memory (Bytes): ", mem
私が得た出力は次のとおりです。
Total number of lines: 30609720
Position: (9745, 2994)
Read 3.26693612356 %.
Memory (Bytes): 64348736
Position: (38857, 103574)
Read 6.53387224712 %.
Memory (Bytes): 128816320
Position: (83609, 63498)
Read 9.80080837067 %.
Memory (Bytes): 192553000
Position: (139692, 1078610)
Read 13.0677444942 %.
Memory (Bytes): 257873392
Position: (205067, 153705)
Read 16.3346806178 %.
Memory (Bytes): 320107588
Position: (283371, 253064)
Read 19.6016167413 %.
Memory (Bytes): 385448716
Position: (354601, 377328)
Read 22.8685528649 %.
Memory (Bytes): 448629828
Position: (441109, 3024112)
Read 26.1354889885 %.
Memory (Bytes): 512208580
500MB のファイルの 25% だけを読み取った後でも、Python は 500MB を消費します。そのため、ファイルの内容を int のタプルのリストとして格納することは、メモリ効率があまり良くないようです。500MB のファイルを 1GB のメモリに読み込むことができるようにするためのより良い方法はありますか?