Python includes a profiler called cProfile .
(Python包含一个名为cProfile的探查器。)
It not only gives the total running time, but also times each function separately, and tells you how many times each function was called, making it easy to determine where you should make optimizations. (它不仅给出了总的运行时间,还分别对每个函数进行了计时,并告诉您每个函数被调用了多少次,从而使您轻松确定应该在哪里进行优化。)
You can call it from within your code, or from the interpreter, like this:
(您可以从代码内部或解释器中调用它,如下所示:)
import cProfile
cProfile.run('foo()')
Even more usefully, you can invoke the cProfile when running a script:
(更有用的是,您可以在运行脚本时调用cProfile:)
python -m cProfile myscript.py
To make it even easier, I made a little batch file called 'profile.bat':
(为了使其更容易,我制作了一个名为“ profile.bat”的批处理文件:)
python -m cProfile %1
So all I have to do is run:
(所以我要做的就是运行:)
profile euler048.py
And I get this:
(我得到这个:)
1007 function calls in 0.061 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.061 0.061 <string>:1(<module>)
1000 0.051 0.000 0.051 0.000 euler048.py:2(<lambda>)
1 0.005 0.005 0.061 0.061 euler048.py:2(<module>)
1 0.000 0.000 0.061 0.061 {execfile}
1 0.002 0.002 0.053 0.053 {map}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler objects}
1 0.000 0.000 0.000 0.000 {range}
1 0.003 0.003 0.003 0.003 {sum}
EDIT: Updated link to a good video resource from PyCon 2013 titled Python Profiling
(编辑:更新了指向PyCon 2013名为Python Profiling的良好视频资源的链接)
Also via YouTube .
(也通过YouTube 。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…