我有一个大文本文件(~450MB -> 129,000 行和 457,000,000 个字符),当我尝试使用此文件一段时间后,内存错误 出现,这是我的代码:
docDict = {}
ind = 1
with open('somefile.txt',encoding='utf-8') as f:
for line in f:
data = line.split(' ')
docDict[ind] = data
ind+=1
我看到了this , 但我逐行读取文件。
请您参考如下方法:
为了测试代码中数据结构的开销,我编写了以下测试程序。它假设您的文本文件是 N 兆字节的 ASCII 编码,并且行相对较短。 (在我的物理内存用完后,我不得不将 N 从 450 更改为 150。)
import sys
MB = 1024 * 1024
line = "the quick brown fox jumps over the lazy dog"
megs = 150
nlines = (megs * MB) / len(line)
d = {}
for i in xrange(nlines):
d[i] = line.split(' ')
dict_size = sys.getsizeof(d)
list_size = sum(sys.getsizeof(a) for a in d.items())
item_size = sum(sum(sys.getsizeof(s) for s in a) for a in d.items())
print " dict:", dict_size / float(MB), "MB"
print "lists:", list_size / float(MB), "MB"
print "items:", item_size / float(MB), "MB"
print "total:", (dict_size + list_size + item_size) / float(MB), "MB"
结果:
dict: 192.00 MB
lists: 251.16 MB
items: 669.77 MB
total: 1112.9 MB
看Activity Monitor,Python进程内存使用超过2G,所以也有一些内存没算进去。 malloc 实现的工件可能是一种可能性。
我用 C++ 实现了相同的程序:
#include <string>
#include <vector>
#include <unordered_map>
int main()
{
int const MB = 1024 * 1024;
std::string const line = "the quick brown fox jumps over the lazy dog";
std::vector<std::string> const split = {
"the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"
};
int const megs = 150;
int const nlines = (megs * MB) / line.size();
std::unordered_map<int, std::vector<std::string>> d;
for (int i = 0; i < nlines; ++i) {
d[i] = split;
}
}
使用 clang++ -O3 编译,这使用了大约 1GB 的内存。 C++ 没有 sys.getsizeof(),所以它需要更多的工作来分解内存使用,而我没有做那项工作。
两倍于等效 C++ 的内存实际上对于 Python 来说是一个相当不错的结果,因此我删除了关于 cPython 实现的预编辑评论。
我认为您的主要问题是将行存储为短字符串数组。您是否可以将这些行存储为整个字符串并根据需要拆分它们,但不是一次全部拆分?
您的计划的最终目标是什么?
