Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。对于Python,有时方法有些笨拙——即向__main__添加计时代码。
描述Python程序运行时间的好方法是什么?
Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。对于Python,有时方法有些笨拙——即向__main__添加计时代码。
描述Python程序运行时间的好方法是什么?
当前回答
还有一个叫做statprof的统计分析器。它是一个采样分析器,因此它为代码增加了最小的开销,并提供了基于行的(而不仅仅是基于函数的)计时。它更适合于游戏等软实时应用,但精度可能低于cProfile。
pypi中的版本有点旧,因此可以通过指定git存储库来使用pip安装:
pip install git+git://github.com/bos/statprof.py@1a33eba91899afe17a8b752c6dfdec6f05dd0c01
您可以这样运行:
import statprof
with statprof.profile():
my_questionable_function()
另请参见https://stackoverflow.com/a/10333592/320036
其他回答
值得指出的是,使用探查器仅在主线程上有效(默认情况下),如果使用它们,您将无法从其他线程获得任何信息。这可能有点棘手,因为探查器文档中完全没有提到它。
如果您还想评测线程,那么您需要查看文档中的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类而不是标准类。它可能会给你更多的灵活性,但我不确定它是否值得,特别是如果你使用的是不使用你的类的第三方代码。
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。
我最近创建了金枪鱼,用于可视化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
Scalene是一个新的python分析器,它涵盖了许多用例,对性能的影响最小:
https://github.com/plasma-umass/scalene
它可以在非常精细的水平上评测CPU、GPU和内存利用率。它还特别支持多线程/并行化的python代码。
添加到https://stackoverflow.com/a/582337/1070617,
我编写了这个模块,允许您使用cProfile并轻松查看其输出。更多信息:https://github.com/ymichael/cprofilev
$ python -m cprofilev /your/python/program
# Go to http://localhost:4000 to view collected statistics.
另请参见:http://ymichael.com/2014/03/08/profiling-python-with-cprofile.html如何理解收集的统计数据。