python - python 真实内存与分析内存

标签 python garbage-collection memory-profiling

使用memory_profiler帮助需要在不同点释放一些内存的项目。开发环境为OS X雪豹。

如下所示,分析的内存峰值约为 414.699 MiB,但事件监视器显示进程峰值几乎是该值的两倍(超过 900 MB )。

    Line #    Mem usage    Increment   Line Contents
================================================
    24   20.441 MiB    0.000 MiB   @profile
    25                             def do_work():
    26                                 "Call each function in order"
    27   20.445 MiB    0.004 MiB       x = audio.AudioQuantumList() 
    28  137.098 MiB  116.652 MiB       audiofile = make_objects("/Users/path/audio/Track01.mp3")
    29  295.480 MiB  158.383 MiB       audiofile2 = make_objects("/Users/path/audio/Track02.mp3")
    30  414.699 MiB  119.219 MiB       audiofile3 = make_objects("/Users/path/audio/Track03.mp3")
    31  414.699 MiB    0.000 MiB       x = add_to_list(audiofile, x)
    32  417.426 MiB    2.727 MiB       audiofile = clear_memory(audiofile)  
    33  417.426 MiB    0.000 MiB       gc.collect()
    34  417.426 MiB    0.000 MiB       x = add_to_list(audiofile2, x)
    35  425.047 MiB    7.621 MiB       audiofile2 = clear_memory(audiofile2)  
    36  285.344 MiB -139.703 MiB       gc.collect()
    37  285.344 MiB    0.000 MiB       x = add_to_list(audiofile3, x)
    38  340.082 MiB   54.738 MiB       audiofile3 = clear_memory(audiofile3)  
    39  339.582 MiB   -0.500 MiB       gc.collect()

内存分析器显示 CPU 实际使用的内存的一半是否正常?这实际上是这里发生的事情吗?

另请注意,当未显式调用 gc.collect 时,在第 36 行释放的 -139.703 MiB 变为:

================================================
35  374.895 MiB  -45.617 MiB       audiofile2 = clear_memory(audiofile2)

最佳答案

在逐行报告中,memory_profiler 测量每行执行后的内存使用情况。在函数内的内存峰值中,例如在 make_objects 内,但在函数返回之前释放内存,则 memory_profiler 将不会报告该使用情况。

解决方法包括装饰嵌套函数(例如 make_objects)或使用 mprof(与 memory_profiler 一起分发)来报告内存使用情况作为时间的函数。

关于python - python 真实内存与分析内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25633845/

相关文章:

python - 如何使用 Python 获取数据库中最后插入记录的主键

java - 如何让 PSOldGen 扩展以容纳非常大的对象?

c - 使用 Visual Studio 2013 在 C 中查找内存泄漏

c# - TimerCallback.PerformTimerCallback 内存分配

python - Networkx:获取节点之间的距离

Python asyncio 缓冲和处理数据

Python iloc 给出 indexError : single positional indexer is out-of-bounds in simple for loop

java - 如何优化外部 Java 库的资源使用?

garbage-collection - 确定 OpenJDK Activity GC 类型

c - 从 Valgrind 源代码访问用户变量