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

其他回答

只有终端(也是最简单的)解决方案,以防所有这些花哨的UI无法安装或运行:完全忽略cProfile并将其替换为pyinstrument,它将在执行后立即收集并显示调用树。

安装:

$ pip install pyinstrument

配置文件和显示结果:

$ python -m pyinstrument ./prog.py

适用于蟒蛇2和3。

[编辑]这里可以找到API的文档,用于分析代码的一部分。

我发现cprofiler和其他资源更多地用于优化目的,而不是调试。

我制作了自己的测试模块,用于简单的python脚本速度测试。(在我的例子中,使用ScriptProfilerPy测试了1K+行py文件,并在几分钟内将代码速度提高了10倍。

模块ScriptProfilerPy()将运行代码,并向其添加时间戳。我把模块放在这里:https://github.com/Lucas-BLP/ScriptProfilerPy

Use:

from speed_testpy import ScriptProfilerPy

ScriptProfilerPy("path_to_your_script_to_test.py").Profiler()

输出:

添加到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类而不是标准类。它可能会给你更多的灵活性,但我不确定它是否值得,特别是如果你使用的是不使用你的类的第三方代码。

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')