Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。对于Python,有时方法有些笨拙——即向__main__添加计时代码。
描述Python程序运行时间的好方法是什么?
Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。对于Python,有时方法有些笨拙——即向__main__添加计时代码。
描述Python程序运行时间的好方法是什么?
当前回答
有很多很好的答案,但它们要么使用命令行,要么使用一些外部程序来分析和/或排序结果。
我真的错过了在IDE(eclipsePyDev)中使用而不接触命令行或安装任何东西的方法。所以就在这里。
无命令行分析
def count():
from math import sqrt
for x in range(10**5):
sqrt(x)
if __name__ == '__main__':
import cProfile, pstats
cProfile.run("count()", "{}.profile".format(__file__))
s = pstats.Stats("{}.profile".format(__file__))
s.strip_dirs()
s.sort_stats("time").print_stats(10)
有关更多信息,请参阅文档或其他答案。
其他回答
添加到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如何理解收集的统计数据。
值得指出的是,使用探查器仅在主线程上有效(默认情况下),如果使用它们,您将无法从其他线程获得任何信息。这可能有点棘手,因为探查器文档中完全没有提到它。
如果您还想评测线程,那么您需要查看文档中的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类而不是标准类。它可能会给你更多的灵活性,但我不确定它是否值得,特别是如果你使用的是不使用你的类的第三方代码。
在Virtaal的源代码中,有一个非常有用的类和装饰器,它可以使分析(甚至对于特定的方法/函数)非常简单。然后可以在KCacheGrind中非常舒适地查看输出。
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')
我发现,如果您不想使用命令行选项,该功能快速且易于使用。
要使用,只需在要分析的每个函数上方添加@profile。
def profile(fnc):
"""
Profiles any function in following class just by adding @profile above function
"""
import cProfile, pstats, io
def inner (*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
retval = fnc (*args, **kwargs)
pr.disable()
s = io.StringIO()
sortby = 'cumulative' #Ordered
ps = pstats.Stats(pr,stream=s).strip_dirs().sort_stats(sortby)
n=10 #reduced the list to be monitored
ps.print_stats(n)
#ps.dump_stats("profile.prof")
print(s.getvalue())
return retval
return inner
每个函数的输出如下
Ordered by: cumulative time
List reduced from 38 to 10 due to restriction <10>
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.002 0.002 3151212474.py:37(get_pdf_page_count)
1 0.000 0.000 0.002 0.002 fitz.py:3604(__init__)
1 0.001 0.001 0.001 0.001 {built-in method fitz._fitz.new_Document}
1 0.000 0.000 0.000 0.000 fitz.py:5207(__del__)
1 0.000 0.000 0.000 0.000 {built-in method fitz._fitz.delete_Document}
1 0.000 0.000 0.000 0.000 fitz.py:4816(init_doc)
1 0.000 0.000 0.000 0.000 fitz.py:5197(_reset_page_refs)
1 0.000 0.000 0.000 0.000 fitz.py:4821(<listcomp>)
11 0.000 0.000 0.000 0.000 fitz.py:4054(_getMetadata)
1 0.000 0.000 0.000 0.000 weakref.py:241(values)