【问题标题】:How does python allocate memory for list & string?python如何为列表和字符串分配内存?
【发布时间】:2021-01-28 13:05:26
【问题描述】:

这是我对 python3 的测试代码:

#! /usr/bin/python3
from memory_profiler import profile

@profile(precision=10)
def f():
    huge_list = [x for x in range(2000)]
    del huge_list
    print("finish")

if __name__ == "__main__":
    f()

输出:

Line #    Mem usage    Increment   Line Contents
================================================
     4  17.2109375000 MiB  17.2109375000 MiB   @profile(precision=10)
     5                             def f():
     6  17.2109375000 MiB   0.0000000000 MiB       huge_list = [x for x in range(2000)]
     7  17.2109375000 MiB   0.0000000000 MiB       del huge_list
     8  17.2226562500 MiB   0.0117187500 MiB       print("finish")

这表明huge_list = [x for x in range(2000)] 不占用任何内存。
我改成huge_list = "aa" * 2000,还是一样。
但如果我将 2000 更改为 20000,它会获得一些内存。

为什么?

这里有一个类似的问题: What does “del” do exactly?

【问题讨论】:

标签: python memory


【解决方案1】:

我不确定事情究竟是如何运作的,但我认为这就是发生的事情:

  • memory-profiler 不会测量解释器实际使用的内存,而是测量整个进程的内存,如memory-profiler 的常见问题解答中所述:

问:结果的准确性如何?
A:该模块通过向操作系统内核查询当前进程分配的内存量来获取内存消耗,这可能与Python解释器实际使用的内存量略有不同。此外,由于垃圾收集器在 Python 中的工作方式,不同平台甚至运行之间的结果可能会有所不同。

  • 如果解释器预先保留了足够的内存,以便新列表适合空闲的保留内存,则进程不需要更多的内存来保留。所以 memory-profiler 正确地打印出 0 的变化。大约 1000 个整数的列表毕竟不是很大,所以如果解释器通常有一些空闲的保留内存悬空,我不会感到惊讶。
  • 如果新的巨大列表所需的内存不适合已保留的内存,则进程需要保留更多,而内存分析器实际上会看到。
  • abarnert 的 answerWhat does “del” do exactly? 基本上是在说同样的话。
  • 尽管如此,我的机器上的结果是不同的(在 win32 和 memory-profiler 0.57.0 上使用 Python 3.8.5、64 位 (AMD64):
     Line #    Mem usage    Increment   Line Contents
     ================================================
     4  41.3984375000 MiB  41.3984375000 MiB   @profile(precision=10)
     5                             def f():
     6  41.4023437500 MiB   0.0039062500 MiB       huge_list = [x for x in range(1)]
     7  41.4023437500 MiB   0.0000000000 MiB       del huge_list
     8  41.4101562500 MiB   0.0078125000 MiB       print("finish")

所以我猜这很大程度上取决于系统....

编辑:

正如莱斯库尔在问题 cmets 中所写:

如果您想对您的应用进行精确的内存跟踪,您应该考虑使用tracemalloc

【讨论】:

    猜你喜欢
    • 2012-07-10
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2016-03-25
    相关资源
    最近更新 更多