为了测试代码中数据结构的开销,我编写了以下测试程序。它假定您的文本文件是 ASCII 编码的N 兆字节,行数相对较短。 (我的物理内存耗尽后,我不得不将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进程的内存使用量超过了2GB,所以也有一些内存没有计入。 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 实现的预编辑 cmets。
我认为您的主要问题是将行存储为短字符串数组。您是否可以将这些行存储为整个字符串并根据需要将它们拆分,但不能一次全部拆分?
你的计划的最终目标是什么?