【问题标题】:What is the reliable method to find most time consuming part of the code?找到代码中最耗时部分的可靠方法是什么?
【发布时间】:2013-11-20 09:15:28
【问题描述】:

沿着我的源代码,我尝试在 Python 中捕获和测量一个段的时间发布。如何以方便的方式准确地测量该段通过时间?

【问题讨论】:

标签: python profiling performance


【解决方案1】:

使用分析器

Python 的cProfile 包含在标准库中。

更方便的方法是使用包profilestats。然后你可以使用装饰器来装饰你想要分析的功能:

from profilestats import profile

@profile
def my_function(args, etc):
    pass

这将导致在 STDOUT 上打印这样的摘要:

         6 function calls in 0.026 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.026    0.026 some_code.py:3(some_func)
        2    0.019    0.010    0.026    0.013 some_code.py:9(expensive_func)
        2    0.007    0.003    0.007    0.003 {range}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

更多有用的信息在生成的cachegrind.out.profilestats 文件中。您可以使用可以可视化 cachegrind 统计信息的工具打开此文件,例如 RunSnakeRun,然后像这样轻松(或更容易)阅读调用堆栈的可视化效果:

更新profilestatspyprof2calltree 的拉取请求已合并,因此它们现在也支持 Python 3.x。

【讨论】:

  • profilestats 支持什么版本的 Python?页面上甚至我看到的任何代码中都没有任何指示......
  • 你是对的,它并没有在它的 PyPi 页面上指明支持的 Python 版本。它只是cProfile 的一个小包装(profilestats.py 基本上是所有代码),但快速浏览它使用file 而不是open 意味着它不能在Python 3.x 上按原样工作。它还取决于 pyprof2calltree,它仅是 2.x。但是,两者都应该可以通过2to3 脚本轻松转换,我猜只是还没有人开始提出拉取请求。
  • Python 3.x 为 pyprof2calltreeprofilestats 完成的拉取请求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2011-01-29
  • 1970-01-01
相关资源
最近更新 更多