简体   繁体   English

Python内存管理 - 字典

[英]Python memory management - dictionary

I have a dictionary saved in a file. 我有一个保存在文件中的字典。 I load the dictionary into memory from a python interactive shell, and my system monitor says that the python process consumes 4GB. 我从python交互式shell将字典加载到内存中,我的系统监视器说python进程消耗4GB。 The following commands give the following outputs: 以下命令提供以下输出:

size1 = sys.getsizeof(mydict)/(1024**2)
print size1

96 96

size2 = 0
for i in mydict.keys():
    size2 += sys.getsizeof(i)
print size2/(1024**2)

37 37

size3 = 0
for i in mydict.keys():
    size3 += sys.getsizeof(mydict[i])
print size3/(1024**2)

981 981

size4 = 0
for i in mydict.keys():
    for j in mydict[i]:
        size4 += j
print size4/(1024**2)

2302 2302

print str(size1 + size2 + size3 + size4)

3416 3416

Now if i delete the dictionary 现在,如果我删除字典

del(mydict)
gc.collect()

less than 400MB are freed from memory. 从内存中释放不到400MB。 Even if i remove first all the items one by one from the lists inside the dictionary, the memory freed is no more than 450-500 MB.. So i end up with no variables in my shell, but still 3,5GB are consumed.. Can anyone explain what is happening? 即使我从字典中的列表中逐个删除所有项目,释放的内存不超过450-500 MB ..所以我最终在我的shell中没有变量,但仍然消耗3,5GB。谁能解释一下发生了什么?

There are two things to keep in mind: 要记住两件事:

Even if you delete the entire object, python might reserve that memory for further use(instead of allocating memory once again later). 即使您删除整个对象,python也可能会保留该内存以供进一步使用(而不是稍后再次分配内存)。 The footprint that python leaves in the os won't significantly change. python在os中留下的足迹不会发生显着变化。

On Linux and UNIX-based systems processes do not necessarily give back the allocated memory until the application dies. 在基于Linux和UNIX的系统上,在应用程序终止之前,进程不一定会返回已分配的内存。

In order to successfully release the memory you might want to take a look at the garbage collector . 为了成功释放内存,您可能需要查看垃圾收集器 With it you can force python to free the allocated memory. 有了它,你可以强制python释放分配的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM