Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

python - 如何配置Python脚本?(How can you profile a Python script?)

Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs.

(欧拉计画和其他编码竞赛经常有最多的运行时间,或者人们吹嘘他们的特定解决方案的运行速度。)

With Python, sometimes the approaches are somewhat kludgey - ie, adding timing code to __main__ .

(使用Python时,有时这些方法有些繁琐-即在__main__添加计时代码。)

What is a good way to profile how long a Python program takes to run?

(剖析Python程序需要花费多长时间的好方法是什么?)

  ask by Chris Lawlor translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...