我在硬盘上有一个只有168MB的文件。它是一个逗号分隔的单词和ID列表。单词可以是1-5个字符长。共有650万行。
我在Python中创建了一个字典,将其加载到内存中,以便可以将传入的文本与该单词列表进行比较。当Python将其加载到内存中时,会显示使用了1.3GB的RAM空间。有什么想法吗?
假设我的单词文件看起来像这样...
1,word1
2,word2
3,word3
然后再加上650万。
然后我通过循环遍历该文件并创建一个字典(Python 2.6.1):
def load_term_cache():
"""will load the term cache from our cached file instead of hitting mysql. If it didn't
preload into memory it would be 20+ million queries per process"""
global cached_terms
dumpfile = os.path.join(os.getenv("MY_PATH"), 'datafiles', 'baseterms.txt')
f = open(dumpfile)
cache = csv.reader(f)
for term_id, term in cache:
cached_terms[term] = term_id
f.close()
仅仅这样做就会使内存占用量激增。我查看了活动监视器,发现它把内存使用最大化,高达约1.5GB的RAM。在我的笔记本电脑上,它只是开始交换空间。有什么办法可以在Python中最有效地存储键值对到内存中吗?
更新:我尝试使用anydb模块,在加载了440万条记录后,它就挂掉了。浮点数是自从我尝试加载它以来经过的秒数。
56.95
3400018
60.12
3600019
63.27
3800020
66.43
4000021
69.59
4200022
72.75
4400023
83.42
4600024
168.61
4800025
338.57
你可以看到它一开始运行得很好。每几秒钟插入20万行,直到我遇到瓶颈,时间加倍。
import anydbm
i=0
mark=0
starttime = time.time()
dbfile = os.path.join(os.getenv("MY_PATH"), 'datafiles', 'baseterms')
db = anydbm.open(dbfile, 'c')
#load from existing baseterm file
termfile = os.path.join(os.getenv("MY_PATH"), 'datafiles', 'baseterms.txt.LARGE')
for line in open(termfile):
i += 1
pieces = line.split(',')
db[str(pieces[1])] = str(pieces[0])
if i > mark:
print i
print round(time.time() - starttime, 2)
mark = i + 200000
db.close()