Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。对于Python,有时方法有些笨拙——即向__main__添加计时代码。
描述Python程序运行时间的好方法是什么?
Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。对于Python,有时方法有些笨拙——即向__main__添加计时代码。
描述Python程序运行时间的好方法是什么?
当前回答
值得指出的是,使用探查器仅在主线程上有效(默认情况下),如果使用它们,您将无法从其他线程获得任何信息。这可能有点棘手,因为探查器文档中完全没有提到它。
如果您还想评测线程,那么您需要查看文档中的threading.setprofile()函数。
您也可以创建自己的线程.Thread子类:
class ProfiledThread(threading.Thread):
# Overrides threading.Thread.run()
def run(self):
profiler = cProfile.Profile()
try:
return profiler.runcall(threading.Thread.run, self)
finally:
profiler.dump_stats('myprofile-%d.profile' % (self.ident,))
并使用ProfiledThread类而不是标准类。它可能会给你更多的灵活性,但我不确定它是否值得,特别是如果你使用的是不使用你的类的第三方代码。
其他回答
Scalene是一个新的python分析器,它涵盖了许多用例,对性能的影响最小:
https://github.com/plasma-umass/scalene
它可以在非常精细的水平上评测CPU、GPU和内存利用率。它还特别支持多线程/并行化的python代码。
cProfile非常适合于分析,而kcachegrind非常适合于可视化结果。中间的pyprov2calltree处理文件转换。
python -m cProfile -o script.profile script.py
pyprof2calltree -i script.profile -o script.calltree
kcachegrind script.calltree
所需的系统包:
kcachegrind(Linux)、qcachegrind(MacOs)
Ubuntu上的设置:
apt-get install kcachegrind
pip install pyprof2calltree
结果:
Python包括一个名为cProfile的分析器。它不仅给出了总的运行时间,而且还分别计算了每个函数的时间,并告诉每个函数被调用了多少次,从而很容易确定应该在哪里进行优化。
您可以从代码内部或从解释器调用它,如下所示:
import cProfile
cProfile.run('foo()')
更有用的是,您可以在运行脚本时调用cProfile:
python -m cProfile myscript.py
为了更简单,我制作了一个名为“profile.bat”的小批处理文件:
python -m cProfile %1
所以我要做的就是跑:
profile euler048.py
我得到了这个:
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}
编辑:更新了2013年PyCon视频资源的链接,标题为Python评测也可以通过YouTube。
gprof2dot_magic公司
gprof2dot的神奇函数,用于在JupyterLab或Jupyter Notebook中将任何Python语句作为DOT图进行评测。
GitHub回购:https://github.com/mattijn/gprof2dot_magic
安装
确保您有Python包gprof2dot_magic。
pip install gprof2dot_magic
它的依赖关系gprof2dot和graphviz也将被安装
用法
要启用magic函数,首先加载gprof2dot_magic模块
%load_ext gprof2dot_magic
然后将任何行语句配置为DOT图,如下所示:
%gprof2dot print('hello world')
我最近创建了金枪鱼,用于可视化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