IPython 2.x中的计时和剖析

2 投票
1 回答
524 浏览
提问于 2025-04-17 20:52

我找到了一篇文章:在IPython中进行计时和性能分析,是2013年3月的,但我在定义和使用一些特殊命令时遇到了问题。我在想,这是不是因为文章里的某些信息现在已经不适用了。

我做了:

$ pip install line-profiler
$ pip install psutil
$ pip install memory_profiler 

然后在我的IPython会话中,我定义了:

import memory_profiler

def load_ipython_extension(ip):
    ip.define_magic('memit', memory_profiler.magic_memit)
    ip.define_magic('mprun', memory_profiler.magic_mprun)

当我尝试运行:

%memit

时,我收到的错误是:错误:行魔法函数未定义。这是为什么呢?

另外,这篇2013年的文章对于IPython 2.x来说还适用吗?

1 个回答

1

你还需要“注册模块”,后面会详细解释。

编辑你的配置文件,路径是 ~/.ipython/profile_default/ipython_config.py,找到相关的部分,取消注释并修改这些列表,添加以下内容:

c.TerminalIPythonApp.extensions = [
'line_profiler_ext',
'memory_profiler_ext', ]
c.InteractiveShellApp.extensions = [
'line_profiler_ext',
'memory_profiler_ext', ]

我这样做的时候成功了,前提是我定义了一个配置文件,并且扩展文件夹是 $IPythonDIR/extensions

如果你是在交互式命令行手动导入这些功能,不太确定该怎么做才能让它生效。

撰写回答