【问题标题】:Measure (max) memory usage with IPython—like timeit but memit使用 IPython 测量(最大)内存使用情况——类似于 timeit 但 memit
【发布时间】:2013-10-06 05:35:49
【问题描述】:

我有一个简单的任务:除了测量在 Python 中执行一段代码所花费的时间之外,我还需要测量一段给定的代码所需的内存量。

IPython 有一个不错的实用程序,名为 timeit,它的工作原理如下:

In [10]: timeit 3 + 3
10000000 loops, best of 3: 24 ns per loop

我正在寻找的是这样的:

In [10]: memit 3 + 3
10000000 loops, best of 3: 303 bytes per loop

我知道这可能不是 IPython 内置的,但我喜欢 timeit-memit 的类比。

【问题讨论】:

  • 我去看看,谢谢;那里的解决方案看起来很简单。关于“最好”的好点子——但 timeit 也给你最好的,你可能会说你真的(有时)对最坏的时间感兴趣。回覆。 IPython 魔法:我找到了blog.vene.ro/2012/06/30/…
  • 这个问题被标记为重复的问题是关于 Python 中的内存分析器的问题——这里的这个问题是关于 IPython 的;所以我看不出它是如何真正重复的......另一个问题没有提到timeitmemit甚至“ipython”。

标签: python memory time ipython benchmarking


【解决方案1】:

事实上,它已经存在,作为实用命名 memory_profiler 包的一部分:

In [2]: %memit np.zeros(1e7)
maximum of 3: 76.402344 MB per loop

更多信息https://github.com/pythonprofilers/memory_profiler#ipython-integration

编辑:要使用它,您首先需要将其作为 IPython 扩展加载:

%load_ext memory_profiler

要使 IPython 在启动时始终加载 memory_profiler 扩展,请将其添加到配置文件的 ipython_config.py 中的 c.InteractiveShellApp.extensions 列表中:

$ grep -C2 c.InteractiveShellApp.extensions ~/.ipython/profile_default/ipython_config.py
 # A list of dotted module names of IPython extensions to load.
 #
 c.InteractiveShellApp.extensions = [
   'autoreload',
   'memory_profiler',

【讨论】:

  • 完成了pip install memory_profilerIn [2]: %memit 3 给了我ERROR: Line magic function %memit` not found`。
  • 有一个 IPython 特定的命令来加载扩展。我已将其添加到答案中。
  • %load_ext memory_profiler 在我的 Jupyter Notebook 中工作之前,我还需要执行 pip install memory_profiler
  • 如果配置文件不存在,在终端运行ipython profile create
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-03
  • 2011-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
相关资源
最近更新 更多