为什么将 pickle 文件加载到内存中会花费更多 space?

Why loading a pickle file into memory will take much more space?

我有一个文件夹包含 pickle.dump 保存的 7603 个文件。平均文件大小为 6.5MB,因此文件占用的总磁盘 space 约为 48GB

每个文件都是通过pickle一个list对象得到的,list的结构是

[A * 50] 
 A = [str, int, [92 floats], B * 3] 
                             B = [C * about 6] 
                                  C = [str, int, [92 floats]]

我用的电脑内存是128GB

但是,我无法通过此脚本将文件夹中的所有文件加载到内存中:

import pickle
import multiprocessing as mp
import sys
from os.path import join
from os import listdir
import os

def one_loader(the_arg):
    with open(the_arg, 'rb') as source:
        temp_fp = pickle.load(source)
    the_hash = the_arg.split('/')[-1]
    os.system('top -bn 1 | grep buff >> memory_log')
    return (the_hash, temp_fp)

def process_parallel(the_func, the_args):
    pool = mp.Pool(25)
    result = dict(pool.map(the_func, the_args))
    pool.close()
    return result

node_list = sys.argv[-1]
db_path =  db_path
the_hashes = listdir(db_path)
the_files = [join(db_path, item) for item in the_hashes]
fp_dict = {}
fp_dict = process_parallel(one_loader, the_files)

我已经绘制了内存使用情况,您可以从脚本中看到,内存使用情况是

我对这个情节有几个困惑:

  1. 4000 个文件占用 25GB 磁盘 space,但为什么它们占用的内存超过 100GB

  2. 在内存使用率突然下降后,我没有收到任何错误,我可以看到脚本仍然是 运行 通过使用 top 命令。但是我完全不知道系统在做什么,剩下的记忆在哪里

那是因为序列化数据在 运行.

时比管理对象所需的内存 space 更少 space

带有字符串的示例:

import pickle

with open("foo","wb") as f:
    pickle.dump("toto",f)

foo 在磁盘上是 14 个字节(包括泡菜头或其他)但在内存中它要大得多:

>>> import sys
>>> sys.getsizeof('toto')
53

对于字典,情况更糟,因为哈希表(和其他东西):

import pickle,os,sys

d = {"foo":"bar"}
with open("foo","wb") as f:
    pickle.dump(d,f)
print(os.path.getsize("foo"))
print(sys.getsizeof(d))

结果:

27
288

所以比例是 1 比 10。