python - 使用 IPython 测量(最大)内存使用情况——类似于 timeit 但 memit

标签 python memory time ipython benchmarking

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

相关文章:

eclipse - 在 Eclipse 中设置内存断点

Java减少内存使用

bash - 时间命令的自定义格式

R shiny slider输入显示时间

mysql - 如何使用MySQL的MAKETIME函数构造小于1小时的负时间?

python - 是否可以在 Google Colaboratory 中进行动画可视化?

python - 如何在 Win 7 64 位上安装 python-Levenshtein 或其他 C/C++ 包

python - 为什么 "raise"和 "del"不是 Python 中的函数?

python - 使用两个循环的 itertools

c++ - 3维数组的重新分配