我在磁盘上有一个只有 168MB 的文件。它只是一个逗号分隔的单词,id 列表。单词长度可以是 1-5 个字符。有 650 万行。
我在 python 中创建了一个字典来将其加载到内存中,这样我就可以根据该单词列表搜索传入的文本。当 python 将其加载到内存中时,它显示已使用 1.3 GB 的 RAM 空间。知道为什么吗?
所以假设我的word文件看起来像这样......
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
你可以看到它运行得很好。每隔几秒插入 200,000 行,直到我撞到墙,时间翻了一番。
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()