python如何为列表和字符串分配内存?

2024-05-13 02:31:24 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我对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?


Tags: infordeflinerangeprofilepython3list
1条回答
网友
1楼 · 发布于 2024-05-13 02:31:24

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

  • 内存分析器不测量解释器实际使用的内存,而是测量整个过程的内存,如memory-profiler的FAQ中所述:

Q: How accurate are the results ?
A: This module gets the memory consumption by querying the operating system kernel about the amount of memory the current process has allocated, which might be slightly different from the amount of memory that is actually used by the Python interpreter. Also, because of how the garbage collector works in Python the result might be different between platforms and even between runs.

  • 如果解释器事先保留了足够的内存,以便新列表可以放入可用的保留内存中,那么进程不需要保留更多内存。所以内存分析器正确地打印出0的更改。大约1000个整数的列表毕竟不是很大,所以如果解释器通常有一些空闲的保留内存,我也不会感到惊讶
  • 如果新的庞大列表所需的内存不适合已保留的内存,则进程需要保留更多内存,内存分析器实际上可以看到这一点
  • 阿巴内特的{a2}到{a3}基本上是在说同样的话
  • 尽管如此,我的机器上的结果还是不同的(在win32上使用Python 3.8.5、64位(AMD64)和内存分析器0.57.0:
     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")

所以我想这在很大程度上取决于系统

编辑:

正如Lescurel在问题评论中所写:

You should consider using tracemalloc if you want precise memory tracing of your app.

相关问题 更多 >