Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。对于Python,有时方法有些笨拙——即向__main__添加计时代码。
描述Python程序运行时间的好方法是什么?
Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。对于Python,有时方法有些笨拙——即向__main__添加计时代码。
描述Python程序运行时间的好方法是什么?
当前回答
@Maxy对这个答案的评论对我帮助很大,我认为它应该得到自己的答案:我已经有了cProfile生成的.pstats文件,我不想用pycallgraph重新运行这些文件,所以我使用了gprof2dot,得到了很好的svgs:
$ sudo apt-get install graphviz
$ git clone https://github.com/jrfonseca/gprof2dot
$ ln -s "$PWD"/gprof2dot/gprof2dot.py ~/bin
$ cd $PROJECT_DIR
$ gprof2dot.py -f pstats profile.pstats | dot -Tsvg -o callgraph.svg
还有BLAM!
它使用点(与pycallgraph使用的相同),因此输出看起来类似。我觉得gprof2dot丢失的信息更少:
其他回答
不久前,我制作了pycallgraph,它从您的Python代码生成可视化。编辑:我已经将示例更新为使用3.3,这是本文撰写时的最新版本。
在pip安装pycallgraph并安装GraphViz之后,您可以从命令行运行它:
pycallgraph graphviz -- ./mypythonscript.py
或者,您可以分析代码的特定部分:
from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput
with PyCallGraph(output=GraphvizOutput()):
code_to_profile()
其中任何一个都将生成类似下图的pycallgraph.png文件:
python wiki是一个用于分析资源的绝佳页面:http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code
python文档也是如此:http://docs.python.org/library/profile.html
如Chris Lawlor所示,cProfile是一个很棒的工具,可以很容易地打印到屏幕上:
python -m cProfile -s time mine.py <args>
或存档:
python -m cProfile -o output.file mine.py <args>
PS>如果您使用的是Ubuntu,请确保安装python配置文件
apt-get install python-profiler
如果输出到文件,可以使用以下工具获得良好的可视化效果
PyCallGraph:创建调用图图像的工具安装:
pip install pycallgraph
run:
pycallgraph mine.py args
视图:
gimp pycallgraph.png
你可以使用任何你喜欢的方式来查看png文件,我使用了gimp不幸的是,我经常
dot:graph对于cairo渲染器位图太大。缩放0.257079以适合
这使我的图像变得难以使用。所以我通常创建svg文件:
pycallgraph -f svg -o pycallgraph.svg mine.py <args>
PS>确保安装graphviz(提供点程序):
pip install graphviz
使用gprof2dot通过@maxy/@quodlibetor绘制替代图形:
pip install gprof2dot
python -m cProfile -o profile.pstats mine.py
gprof2dot -f pstats profile.pstats | dot -Tsvg -o mine.svg
如果你想做一个累积分析器,意思是连续运行函数几次并观察结果的总和。
您可以使用此cumulative_profiler装饰器:
它是python>=3.6特定的,但您可以删除非本地的,因为它可以在旧版本上工作。
import cProfile, pstats
class _ProfileFunc:
def __init__(self, func, sort_stats_by):
self.func = func
self.profile_runs = []
self.sort_stats_by = sort_stats_by
def __call__(self, *args, **kwargs):
pr = cProfile.Profile()
pr.enable() # this is the profiling section
retval = self.func(*args, **kwargs)
pr.disable()
self.profile_runs.append(pr)
ps = pstats.Stats(*self.profile_runs).sort_stats(self.sort_stats_by)
return retval, ps
def cumulative_profiler(amount_of_times, sort_stats_by='time'):
def real_decorator(function):
def wrapper(*args, **kwargs):
nonlocal function, amount_of_times, sort_stats_by # for python 2.x remove this row
profiled_func = _ProfileFunc(function, sort_stats_by)
for i in range(amount_of_times):
retval, ps = profiled_func(*args, **kwargs)
ps.print_stats()
return retval # returns the results of the function
return wrapper
if callable(amount_of_times): # incase you don't want to specify the amount of times
func = amount_of_times # amount_of_times is the function in here
amount_of_times = 5 # the default amount
return real_decorator(func)
return real_decorator
实例
剖析函数baz
import time
@cumulative_profiler
def baz():
time.sleep(1)
time.sleep(2)
return 1
baz()
baz跑了5次并打印了以下内容:
20 function calls in 15.003 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
10 15.003 1.500 15.003 1.500 {built-in method time.sleep}
5 0.000 0.000 15.003 3.001 <ipython-input-9-c89afe010372>:3(baz)
5 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
指定次数
@cumulative_profiler(3)
def baz():
...
我最近创建了金枪鱼,用于可视化Python运行时和导入配置文件;这在这里可能会有所帮助。
使用安装
pip install tuna
创建运行时配置文件
python3 -m cProfile -o program.prof yourfile.py
或导入配置文件(需要Python 3.7+)
python3 -X importprofile yourfile.py 2> import.log
那就把金枪鱼放在档案里
tuna program.prof
pprofile文件
line_profiler(此处已介绍)也启发了pprofile,其描述如下:
行粒度、线程感知确定性和统计纯python剖面仪
它提供了line_profiler的行粒度,是纯Python,可以用作独立命令或模块,甚至可以生成callgrind格式的文件,这些文件可以很容易地使用[k|q]cachegrind进行分析。
vprof公司
还有vprof,一个Python包,描述如下:
[…]为各种Python程序特性(如运行时间和内存使用)提供丰富的交互式可视化。