我有一个简单的任务:除了测量在 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
的类比。
最佳答案
事实上,它已经存在,作为实用命名的 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',
关于python - 使用 IPython 测量(最大)内存使用情况——类似于 timeit 但 memit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19092812/