Python 分析:使用 line_profiler 的 @profile 装饰器会导致错误

5 python profiling

我正在尝试使用该line_profiler模块分析一些 Python 代码,但无法让它工作。我使用的是 Windows 7 并使用 Python 2.7.6。

当运行kernprof -l -v test.py以下test.py文件时:

@profile
def test():
    a = 1
    b = 1
    return a + b

if __name__ == '__main__':
    print test()
Run Code Online (Sandbox Code Playgroud)

我得到:

C:\>kernprof -l -v C:\test.py
Wrote profile results to test.py.lprof
Timer unit: 3.01262e-07 s

Traceback (most recent call last):
  File "C:\path_to_kernprof\kernprof-script.py", line 10, in <module>
    sys.exit(main())
  File "C:\path_to_kernprof\kernprof.py", line 221, in main
    execfile(script_file, ns, ns)
  File "C:\test.py", line 1, in <module>
    @profile
NameError: name 'profile' is not defined
Run Code Online (Sandbox Code Playgroud)

显然,如果我注释掉包含line_profiler's @profile 装饰器的行,代码将运行良好。我在这里做错了什么?

xgd*_*gsc 2

可能与 python 2 和 future 有关,请参阅错误报告,拉取请求修复了此问题。在将新版本上传到 pypi 之前,您可以根据该提交相应地修改代码。