Python Memory Profiler结果与预期不同

时间:2018-03-02 02:55:04

标签: python

我试图理解在我的python应用程序上使用memory_profiler。 参考Python memory profile guide我复制了以下代码段: -

from memory_profiler import profile

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

根据链接的预期结果是: -

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

但是当我在运行Ubuntu 16.04的VM上运行它时,我得到了以下结果: -

Line #    Mem usage    Increment   Line Contents
================================================
 3     35.4 MiB     35.4 MiB   @profile
 4                             def my_func():
 5     43.0 MiB      7.7 MiB       a = [1] * (10 ** 6)
 6    195.7 MiB    152.6 MiB       b = [2] * (2 * 10 ** 7)
 7     43.1 MiB   -152.5 MiB       del b
 8     43.1 MiB      0.0 MiB       return a

在预期和我的跑步之间似乎存在大约30MiB差异的巨大开销。我试图了解它来自何处,以及我做错了什么。我应该担心吗?

如果有人有任何想法,请提供建议。感谢

编辑:

O / S:在VM内部运行的Ubuntu 16.06.4(Xenial)

Python:Python 3.6.4 :: Anaconda,Inc。

1 个答案:

答案 0 :(得分:0)

列表占用的内存或整数在很大程度上取决于python版本/ build。

例如,在python 3中,所有整数都是长整数,而在python 2中,只有当整数不适合CPU寄存器/ C int时才使用long。

在我的机器上,python 2:

>>> sys.getsizeof(2)
24

Python 3.6.2:

>>> sys.getsizeof(2)
28

在计算比率与24/28比率时,它非常接近:

>>> 195.7/166.2
1.177496991576414
>>> 28/24
1.1666666666666667

(这可能不是唯一的区别,但这是我能想到的最明显的)

所以不,只要结果是成比例的,你就不用担心,但如果你有python整数的内存问题(python 3,那就是),你可以使用替代方法,比如numpy或其他本机整数类型。