python - Python 的 json 模块占用大量内存?

标签 python json memory-leaks

当我将文件加载到 json 中时,python 的内存使用量激增至大约 1.8GB,我似乎无法释放该内存。我整理了一个非常简单的测试用例:

with open("test_file.json", 'r') as f:
    j = json.load(f)

很抱歉,我无法提供示例 json 文件,我的测试文件包含很多敏感信息,但对于上下文,我正在处理一个大约 240MB 的文件。运行以上两行后,我使用了前面提到的 1.8GB 内存。如果我然后执行 del j 内存使用根本不会下降。如果我用 gc.collect() 跟随它,它仍然不会掉落。我什至尝试卸载 json 模块并运行另一个 gc.collect。

我正在尝试运行一些内存分析,但 heapy 已经 100% 占用 CPU 大约一个小时,而且还没有产生任何输出。

有人有什么想法吗?我也尝试过使用 cjson 而不是打包的 json 模块进行上述操作。 cjson 使用的内存减少了大约 30%,但在其他方面显示了完全相同的问题。

我在 Ubuntu 服务器 11.10 上运行 Python 2.7.2。

我很乐意加载任何内存分析器,看看它是否比 heapy 做得更好,并提供您可能认为必要的任何诊断。我正在四处寻找一个大型测试 json 文件,我可以提供给其他任何人试一试。

最佳答案

我认为这两个链接解决了一些有趣的问题,这不一定是一个 json 问题,而只是一个“大对象”问题以及内存如何与 python 和操作系统一起工作

参见 Why doesn't Python release the memory when I delete a large object?为什么从 python 释放的内存不一定由操作系统反射(reflect):

If you create a large object and delete it again, Python has probably released the memory, but the memory allocators involved don’t necessarily return the memory to the operating system, so it may look as if the Python process uses a lot more virtual memory than it actually uses.

关于running large object processes in a subprocess让操作系统处理清理工作:

The only really reliable way to ensure that a large but temporary use of memory DOES return all resources to the system when it's done, is to have that use happen in a subprocess, which does the memory-hungry work then terminates. Under such conditions, the operating system WILL do its job, and gladly recycle all the resources the subprocess may have gobbled up. Fortunately, the multiprocessing module makes this kind of operation (which used to be rather a pain) not too bad in modern versions of Python.

关于python - Python 的 json 模块占用大量内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11057712/

相关文章:

iphone - 在iphone中使用json解析文本文件

c# - 如何在 C#/.NET 中创建内存泄漏

python - 无法使用 Selenium 登录

python - 正则表达式:查找单词但不允许重复

python - 如何在 python 中将 unicode 字符串(来自 JSON 的字符串)编码为 'utf-8'?

c++ - 跟踪 C++ 中的内存使用情况并评估内存消耗

android - Leakcanary 使用 AppCompatActivity 和 FragmentStatePagerAdapter 显示 fragment 泄漏

python - Python中生成支架模型列表的算法

python - 在python中使用全局变量

php - 没有反斜杠的 Laravel JSON 响应