简体   繁体   English

Python memory_profiler:内存使用量不累加

[英]Python memory_profiler: memory usages does not add up

The documentation for memory_profiler offers a simple example showing the changes in memory usage due to creating and deleting a list. memory_profiler的文档提供了一个简单的示例,该示例显示了由于创建和删除列表而导致的内存使用变化。

from memory_profiler import profile

@profile
def my_func():
    a = [1] * (10 ** 6)
    b = [2] * (2 * 10 ** 7)
    del b
    return a

if __name__ == '__main__':
    my_func()

Which produces the following output: 产生以下输出:

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

When b is deleted, its memory usage is freed up. 删除b ,将释放其内存使用量。 I was playing around and changed the example to the following, where I also delete a . 我正在玩耍,并将示例更改为以下示例,其中还删除a

from memory_profiler import profile

@profile
def my_func():
    a = [1] * (10 ** 6)
    b = [2] * (2 * 10 ** 7)
    del a
    del b
    return None

if __name__ == '__main__':
    my_func()

Here, however, deletion of a is not accompanied - as I would naively expect - by a decrease in memory usage. 但是,在这里,删除a并不会(如我天真地期望的那样)伴随内存使用量的减少。 In fact, it seems as though nothing is happening. 实际上,似乎什么也没有发生。

Line #    Mem usage    Increment   Line Contents
================================================
    12     25.1 MiB      0.0 MiB   @profile
    13                             def my_func():
    14     32.7 MiB      7.6 MiB       a = [1] * (10 ** 6)
    15    185.3 MiB    152.6 MiB       b = [2] * (2 * 10 ** 7)
    16    185.3 MiB      0.0 MiB       del a
    17     32.7 MiB   -152.6 MiB       del b
    18     32.7 MiB      0.0 MiB       return None

What is going on? 到底是怎么回事?

del a does in fact not delete the object, it merely marks the object as not used but it will be deleted later, whenever the garbage collector deems it appropriate. 实际上, del a并不会删除该对象,它只是将对象标记为未使用,但是只要垃圾收集器认为合适,它就会在以后删除。 b is big enough to make the garbage collector delete it immediately, but apparently not so for a b足够大,可以使垃圾收集器立即将其删除,但是对于a来说显然不是这样

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

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