【问题标题】:python memory allocation tracepython内存分配跟踪
【发布时间】:2012-12-16 22:58:00
【问题描述】:

我的代码持续分配内存(每秒约 12kb)。运行时间为 8 小时,内存很大!

因此,我想跟踪我的 python 代码分配内存的时刻/代码行。

您可以通过以下方式处理已处理的代码行:

python -m trace --count -C ./tmp code.py

这会生成一个视图,您可以在其中查看该行的执行频率。它看起来像:

code.cover

1:     import sys
1:     import os
1534:  while 1:
1534:      print "foo"

我需要这个来分配内存。如果可能的话,像

1245 B    import sys
893 B     import os
17.46 KB  import somecode

【问题讨论】:

标签: python memory allocation


【解决方案1】:

看起来这个问题已经在这里回答了:Python memory profiler

也许这个可以帮助你:http://pypi.python.org/pypi/memory_profiler

从文档中,执行将选项-m memory_profiler 传递给python 解释器的代码以加载memory_profiler 模块并打印到stdout 逐行分析。如果文件名是 example.py,这将导致:

$ python -m memory_profiler example.py

输出如下:

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

【讨论】:

  • 这很有帮助,但我需要比较一下我的内存使用情况,因为有很多线程循环。所以如果我退出代码,我会看到在运行时这个函数分配了 25 MB 内存
  • 您是否注意到指向类似问题的链接?那里有更多的工具。
猜你喜欢
  • 1970-01-01
  • 2010-10-28
  • 2012-06-10
  • 1970-01-01
  • 2022-09-27
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多