[英]Measure (max) memory usage with IPython—like timeit but memit
我有一個簡單的任務:除了測量在 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',
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.