我使用Python的dict类型来存储一个密钥超过550k的数据文件,几乎是29M,但是在读取数据文件之后,使用的内存超过70M,这是不正常的。你知道吗
那么,这是怎么发生的呢?你知道吗
下面是读取数据文件的函数。你知道吗
def _update_internal_metrics(self, signum, _):
"""Read the dumped metrics file"""
logger.relayindex('reload dumped file begins')
dumped_metrics_file_path = os.path.join(settings.DATA_DIR,
settings.DUMPED_METRICS_FILE)
epoch = int(time.time())
try:
new_metrics = {}
with open(dumped_metrics_file_path) as dumped_metrics_file:
for line in dumped_metrics_file:
line = line.strip()
new_metrics[line] = epoch
except Exception:
if not signum:
self._reload_dumped_file()
logger.relayindex("Dumped metrics file does not exist or can"
"not be read. No update")
else:
settings["metrics"] = new_metrics
instrumentation.increment('dumped.Reload')
logger.relayindex('reload dumped file ends')
首先,
top
不是检查它的正确方法,因为它会告诉您整个过程的内存消耗。您可以从sys
模块使用getsizeof
:其次,字符串和哈希表都有一些开销:
在我的系统上,这是
24
字节开销,不管字符串大小如何,开销都是一致的。有55万把钥匙,头顶13米。你知道吗Python试图保持哈希表不太密集,因为那样会占用查找时间。AFAIK
cpython
实现使用2倍的增长因子,表大小为2^k。由于您的密钥大小刚好大于2倍(math.log(550000,2) # 19.06
),因此它相对稀疏,只有2 ** 20 = 1048576
个插槽。在64位系统上,每个字符串有8个字节的对象指针,这是额外的8M开销。还存储原始文件中没有的整数(另一个8M),每个哈希表槽还包含存储的哈希值(另一个8M)。参见PyDictEntry的来源。你知道吗总共是66M,当然你需要一些空间来存放你的python应用程序的其余部分。我觉得一切都很好。你知道吗
相关问题 更多 >
编程相关推荐