【发布时间】:2014-04-24 06:40:40
【问题描述】:
我有一个大字典,其结构如下:
dcPaths = {'id_jola_001': CPath instance}
其中CPath是自定义类:
class CPath(object):
def __init__(self):
# some attributes
self.m_dAvgSpeed = 0.0
...
# a list of CNode instance
self.m_lsNodes = []
其中 m_lsNodes 是 CNode 的列表:
class CNode(object):
def __init__(self):
# some attributes
self.m_nLoc = 0
# a list of Apps
self.m_lsApps = []
这里m_lsApps是一个CApp的列表,是另一个自定义类:
class CApp(object):
def __init__(self):
# some attributes
self.m_nCount= 0
self.m_nUpPackets = 0
我使用 cPickle 序列化这个字典:
def serialize2File(strFileName, strOutDir, obj):
if len(obj) != 0:
strOutFilePath = "%s%s" % (strOutDir, strFileName)
with open(strOutFilePath, 'w') as hOutFile:
cPickle.dump(obj, hOutFile, protocol=0)
return strOutFilePath
else:
print("Nothing to serialize!")
它工作正常,序列化文件的大小约为 6.8GB。但是,当我尝试反序列化此对象时:
def deserializeFromFile(strFilePath):
obj = 0
with open(strFilePath) as hFile:
obj = cPickle.load(hFile)
return obj
我发现它消耗超过 90GB 的内存并且需要很长时间。
- 为什么会发生这种情况?
- 有什么办法可以优化这个吗?
顺便说一句,我使用的是 python 2.7.6
【问题讨论】:
-
进程在将数据转储到pickle之前消耗了多少内存?
-
这可能取决于存储类的定义方式,因此添加代码会有所帮助。
-
你确定是反序列化吗?众所周知,序列化会占用更多内存来处理循环引用。
-
1.您能告诉我们:最常用的对象是哪种类型? 2. 你能用最低的协议转储它并显示/链接一些更小的块吗? 3. 你使用 Python 3 吗? 4.如果用pickle,问题还存在吗?
-
@bereal 我添加了存储类的代码