Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。对于Python,有时方法有些笨拙——即向__main__添加计时代码。
描述Python程序运行时间的好方法是什么?
Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。对于Python,有时方法有些笨拙——即向__main__添加计时代码。
描述Python程序运行时间的好方法是什么?
当前回答
一个很好的评测模块是line_profiler(使用kernprof.py脚本调用)。它可以在这里下载。
我的理解是,cProfile只提供每个函数花费的总时间的信息。因此,单独的代码行是不定时的。这是科学计算中的一个问题,因为通常一条线会花费很多时间。而且,我记得,cProfile没有抓住我在say numpy.dot上花费的时间。
其他回答
Scalene是一个新的python分析器,它涵盖了许多用例,对性能的影响最小:
https://github.com/plasma-umass/scalene
它可以在非常精细的水平上评测CPU、GPU和内存利用率。它还特别支持多线程/并行化的python代码。
还值得一提的是GUI cProfile转储查看器RunSnakeRun。它允许您排序和选择,从而放大程序的相关部分。图片中矩形的大小与所用时间成正比。如果您将鼠标悬停在一个矩形上,它将突出显示表中的调用以及地图上的任何位置。双击矩形时,它会放大该部分。它将显示谁调用了该部分以及该部分调用了什么。
描述性信息非常有用。它向您显示了该位的代码,当您处理内置库调用时,该代码会很有用。它告诉要查找代码的文件和行。
还想指出,OP说的是“剖析”,但似乎他是指“时机”。请记住,程序在评测时运行速度会变慢。
对于像austin这样的统计分析器,不需要检测,这意味着您可以简单地使用
austin python3 my_script.py
原始输出不是很有用,但您可以将其传输到flamegraph.pl以获得该数据的火焰图表示,该火焰图提供了时间(以微秒为单位的实时)的细分。
austin python3 my_script.py | flamegraph.pl > my_script_profile.svg
或者,您也可以使用web应用程序Speedscope.app快速可视化收集的样本。如果您安装了pprof,还可以获取austin python(例如,pipx安装austin python)并使用austin2prof转换为pprof格式。
然而,如果您安装了VS Code,您可以使用Austin扩展来获得更交互式的体验,包括源代码热图、顶级函数和收集的调用堆栈
如果您想使用终端,也可以使用TUI,它也具有实时图形模式:
只有终端(也是最简单的)解决方案,以防所有这些花哨的UI无法安装或运行:完全忽略cProfile并将其替换为pyinstrument,它将在执行后立即收集并显示调用树。
安装:
$ pip install pyinstrument
配置文件和显示结果:
$ python -m pyinstrument ./prog.py
适用于蟒蛇2和3。
[编辑]这里可以找到API的文档,用于分析代码的一部分。
如果你想做一个累积分析器,意思是连续运行函数几次并观察结果的总和。
您可以使用此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():
...