交互式Python:虽然正确导入了line_profiler,但无法使`%lprun`正常工作

时间:2013-11-13 00:10:34

标签: python profiling ipython spyder magic-function

问题

大多数iPython“魔术功能”对我来说都很好用:%hist%time%prun等等。但是,我注意到%lprun无法可以在我最初安装的时候找到iPython。

尝试解决

然后我发现我应该安装line_profiler模块。我已经安装了这个模块,但似乎仍然无法使魔术功能正常工作。如果我试图调用%lprun,iPython仍然无法找到该功能。如果我用全名(line_profiler.magic_lprun)来调用它,可以找到该函数,但我根本无法使用它。下面是我所做的一个例子(从“Python for Data Analysis”一书中逐步采用):

使用%prun

成功

[在:]

def add_and_sum(x, y):
    added = x + y
    summed = added.sum(axis=1)
    return summed

x = randn(3000, 3000)
y = randn(3000, 3000)

add_and_sum(x, y)

有了这个,我得到了一个很好的答案,正如预期的那样:

[输出:

array([-23.6223074 , -10.08590736, -31.2957222 , ..., -14.17271747,
    63.84057725, -50.28469621])

我可以进行分析魔术功能%prun

[在:]

%prun add_and_sum(x, y)

[输出:

6 function calls in 0.042 seconds

Ordered by: internal time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.020    0.020    0.029    0.029 <ipython-input-27-19f64f63ba0a>:1(add_and_sum)
    1    0.013    0.013    0.042    0.042 <string>:1(<module>)
    1    0.009    0.009    0.009    0.009 {method 'reduce' of 'numpy.ufunc' objects}
    1    0.000    0.000    0.009    0.009 _methods.py:16(_sum)
    1    0.000    0.000    0.009    0.009 {method 'sum' of 'numpy.ndarray' objects}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

使用%lprun

失败

但是当我尝试%lprun时,我无法得到任何东西:

[在:]

%lprun -f add_and_sum add_and_sum(x, y)

[输出:

ERROR: Line magic function `%lprun` not found.

如果我尝试使用其标准名称调用该函数,它也不起作用:

[在:]

line_profiler.magic_lprun -f add_and_sum.test test.add_and_sum(x, y)

[输出:

line_profiler.magic_lprun -f add_and_sum.test test.add_and_sum(x, y)
                                       ^
SyntaxError: invalid syntax

但是图书馆已经正确导入,或者至少就是这样说的:

[在:]

line_profiler

[输出:

<module 'line_profiler' from '/Users/<edit>/anaconda/lib/python2.7/site-packages/line_profiler-1.0b3-py2.7-macosx-10.5-x86_64.egg/line_profiler.pyc'>

[在:]

line_profiler.magic_lprun

[输出:

<function line_profiler.magic_lprun>

似乎我应该配置一些额外的东西,以便我添加的这些新的魔术功能可以被识别出来。我无法通过网络搜索找到任何内容。

我正在运行Spyder作为IDE(仍然使用iPython作为控制台),但我也直接尝试使用iPython和iPython笔记本。我没有任何格式的运气。

2 个答案:

答案 0 :(得分:57)

要使%lprun正常工作,您需要使用以下命令将扩展加载到会话中:

In [1]: %load_ext line_profiler

查看this notebook以查看一些使用魔法的示例。

此外,如果您正在使用Spyder,还有第三方line_profiler插件,您可以找到here

答案 1 :(得分:15)

您有两种方法可以完成工作%lprun,一种解决方案是暂时的,即它会持续到您完成ipython会话,而另一种解决方案是永久性的。

时间:(如Carlos Cordoba的回答)

启动ipython后运行以下内容:

In [1]: %load_ext line_profiler

<强>常驻:

将以下行添加到~/.ipython/profile_default/ipython_config.py

c.TerminalIPythonApp.extensions = [
    'line_profiler',
]

如果您没有文件~/.ipython/profile_default/ipython_config.py,可以按照this获取更多信息来创建文件):

ipython profile create