试图理解python内存分析器

Unn*_*nni 2 python memory-profiling

我使用的内存分析器模块来获取我的Python代码后的内存使用这个答案。但是,我无法解释%memitmagic的输出(或使用@profile模块中的装饰器的输出或mprof run就此而言)。

例如,

%memit range(10000) 
Run Code Online (Sandbox Code Playgroud)

给我 peak memory: 97.41 MiB, increment: 0.24 MiB

尽管,

%memit xrange(10000)
Run Code Online (Sandbox Code Playgroud)

显示peak memory: 97.46 MiB, increment: 0.00 MiB。我确实理解xrange返回一个xrange typerange()返回一个列表之间的区别。我在这里使用它们只是为了演示这两个场景。

我的问题是

  1. 是什么peak memoryincrement实际上意味着什么呢?
  2. 我应该从这个输出报告什么作为脚本(或函数)的总内存使用量?

Ken*_*Wei 5

峰值内存是指你的系统在程序运行时的峰值内存使用量(包括其他进程的内存使用量)。

Increment 是内存使用量相对于程序运行前的内存使用量的增量(即increment= peak memory- starting memory)。

所以你会报告increment。峰值内存只是帮助您计算在程序运行期间使用所有 RAM 的接近程度。

如果您参考自述文件使用部分中的逐行示例:

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
Run Code Online (Sandbox Code Playgroud)

%memit 本质上是给你第 6 行的内存使用量,但报告相对于第 4 行的增量(实际上是第 1 行,但大概第 1-3 行没有计算)。