39

我有一个简单的任务:除了测量在 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类比。

4

1 回答 1

55

事实上,它已经存在,作为实用命名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 扩展,请将其添加到c.InteractiveShellApp.extensions配置文件的列表中ipython_config.py

$ 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',
于 2013-10-01T00:16:20.563 回答