Python Profilers 分析器
***********************

**源代码：** Lib/profile.py 和 Lib/pstats.py

======================================================================


profile分析器简介
=================

"cProfile" 和 "profile" 提供了 Python 程序的 *确定性性能分析* 。
*profile* 是一组统计数据，描述程序的各个部分执行的频率和时间。这些统计
数据可以通过 "pstats" 模块格式化为报表。

Python 标准库提供了同一分析接口的两种不同实现：

1. 对于大多数用户，建议使用 "cProfile" ；这是一个 C 扩展插件，因为其合
   理的运行开销，所以适合于分析长时间运行的程序。该插件基于 "lsprof"
   ，由 Brett Rosen 和 Ted Chaotter 贡献。

2. "profile" 是一个纯 Python 模块（"cProfile" 就是模拟其接口的 C 语言
   实现），但它会显著增加配置程序的开销。如果你正在尝试以某种方式扩展
   分析器，则使用此模块可能会更容易完成任务。该模块最初由 Jim Roskind
   设计和编写。

注解:

  profiler 分析器模块被设计为给指定的程序提供执行概要文件，而不是用于
  基准测试目的（ "timeit" 才是用于此目标的，它能获得合理准确的结果）。
  这特别适用于将 Python 代码与 C 代码进行基准测试：分析器为Python 代码
  引入开销，但不会为 C级别的函数引入开销，因此 C 代码似乎比任何Python
  代码都更快。


实时用户手册
============

本节是为 “不想阅读手册” 的用户提供的。它提供了非常简短的概述，并允许用
户快速对现有应用程序执行评测。

要分析采用单个参数的函数，可以执行以下操作：

   import cProfile
   import re
   cProfile.run('re.compile("foo|bar")')

（如果 "cProfile" 在您的系统上不可用，请使用 "profile" 。）

上述操作将运行 "re.compile()" 并打印分析结果，如下所示：

         197 function calls (192 primitive calls) in 0.002 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.001    0.001 <string>:1(<module>)
        1    0.000    0.000    0.001    0.001 re.py:212(compile)
        1    0.000    0.000    0.001    0.001 re.py:268(_compile)
        1    0.000    0.000    0.000    0.000 sre_compile.py:172(_compile_charset)
        1    0.000    0.000    0.000    0.000 sre_compile.py:201(_optimize_charset)
        4    0.000    0.000    0.000    0.000 sre_compile.py:25(_identityfunction)
      3/1    0.000    0.000    0.000    0.000 sre_compile.py:33(_compile)

第一行显示监听了197个调用。在这些调用中，有192个是 *原始的* ，这意味着
调用不是通过递归引发的。下一行: "Ordered by: standard name" ，表示最右
边列中的文本字符串用于对输出进行排序。列标题包括：

ncalls
   调用次数

tottime
   在指定函数中消耗的总时间（不包括调用子函数的时间）

percall
   是 "tottime" 除以 "ncalls" 的商

cumtime
   指定的函数及其所有子函数（从调用到退出）消耗的累积时间。这个数字对
   于递归函数来说是准确的。

percall
   是 "cumtime" 除以原始调用（次数）的商（即：函数运行一次的平均时间）

filename:lineno(function)
   提供相应数据的每个函数

如果第一列中有两个数字（例如3/1），则表示函数递归。第二个值是原始调用
次数，第一个是调用的总次数。请注意，当函数不递归时，这两个值是相同的，
并且只打印单个数字。

profile 运行结束时，打印输出不是必须的。也可以通过为 "run()" 函数指定
文件名，将结果保存到文件中：

   import cProfile
   import re
   cProfile.run('re.compile("foo|bar")', 'restats')

"pstats.Stats" 类从文件中读取 profile 结果，并以各种方式对其进行格式化
。

"cProfile" 和 "profile" 文件也可以作为脚本调用，以分析另一个脚本。例如
：

   python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)

"-o" 将profile 结果写入文件而不是标准输出

"-s" 指定 "sort_stats()" 排序值之一以对输出进行排序。这仅适用于未提供
"-o" 的情况

"-m" 指定要分析的是模块而不是脚本。

   3.7 新版功能: "cProfile" 添加 "-m" 选项

   3.8 新版功能: "profile" 添加 "-m" 选项

"pstats" 模块的 "Stats" 类具有各种方法用来操纵和打印保存到性能分析结果
文件的数据。

   import pstats
   from pstats import SortKey
   p = pstats.Stats('restats')
   p.strip_dirs().sort_stats(-1).print_stats()

"strip_dirs()" 方法移除了所有模块名称中的多余路径。 "sort_stats()" 方
法按照打印出来的标准模块/行/名称对所有条目进行排序。 "print_stats()"
方法打印出所有的统计数据。 你可以尝试下列排序调用:

   p.sort_stats(SortKey.NAME)
   p.print_stats()

第一个调用实际上将按函数名称对列表进行排序，而第二个调用将打印出统计数
据。 下面是一些可以尝试的有趣调用:

   p.sort_stats(SortKey.CUMULATIVE).print_stats(10)

这将按一个函数中的累计时间对性能分析数据进行排序，然后只打印出最重要的
十行。 如果你了解哪些算法在耗费时间，上面这一行就是你应该使用的。

如果你想要看看哪些函数的循环次数多，且耗费时间长，你应当这样做:

   p.sort_stats(SortKey.TIME).print_stats(10)

以按照每个函数耗费的时间进行排序，然后打印前十个函数的统计数据。

你也可以尝试：

   p.sort_stats(SortKey.FILENAME).print_stats('__init__')

这将按照文件名对所有统计数据进行排序，然后只打印出类初始化方法的统计数
据 (因为它们的名称中都有 "__init__")。 作为最后一个例子，你可以尝试:

   p.sort_stats(SortKey.TIME, SortKey.CUMULATIVE).print_stats(.5, 'init')

这一行以时间为主键，并以累计时间为次键进行排序，然后打印出部分统计数据
。 具体来说，该列表首先被缩减至原始大小的 50% (即: ".5")，然后只保留包
含 "init" 的行，并打印该子列表。

如果你想知道有哪些函数调用了上述函数，你现在就可以做 ("p" 仍然会按照最
后一个标准进行排序):

   p.print_callers(.5, 'init')

这样你将得到每个被列出的函数的调用方列表。

如果你想要更多的功能，你就必须阅读手册，或者自行猜测下列函数的作用:

   p.print_callees()
   p.add('restats')

作为脚本发起调用，"pstats" 模块是一个用于读取和性能分析转储文件的统计
数据浏览器。 它有一个简单的面向行的界面（使用 "cmd" 实现）和交互式的帮
助。


"profile" 和 "cProfile" 模块参考
================================

"profile" 和 "cProfile" 模块都提供下列函数：

profile.run(command, filename=None, sort=-1)

   此函数接受一个可被传递给 "exec()" 函数的单独参数，以及一个可选的文
   件名。 在所有情况下这个例程都会执行:

      exec(command, __main__.__dict__, __main__.__dict__)

   并收集执行过程中的性能分析统计数据。 如果未提供文件名，则此函数会自
   动创建一个 "Stats" 实例并打印一个简单的性能分析报告。 如果指定了
   sort 值，则它会被传递给这个 "Stats" 实例以控制结果的排序方式。

profile.runctx(command, globals, locals, filename=None, sort=-1)

   此函数类似于 "run()"，带有为 *command* 字符串提供全局和局部字典的附
   加参数。 这个例程会执行:

      exec(command, globals, locals)

   并像在上述的 "run()" 函数中一样收集性能分析数据。

class profile.Profile(timer=None, timeunit=0.0, subcalls=True, builtins=True)

   这个类通常只在需要比 "cProfile.run()" 函数所能提供的更精确的性能分
   析控制时被使用。

   可以通过 *timer* 参数提供一个自定义计时器来测量代码运行花费了多长时
   间。 它必须是一个返回代表当前时间的单个数字的函数。 如果该数字为整
   数，则 *timeunit* 指定一个表示每个时间单位持续时间的乘数。 例如，如
   果定时器返回以千秒为计量单位的时间值，则时间单位将为 ".001"。

   直接使用 "Profile" 类将允许格式化性能分析结果而无需将性能分析数据写
   入到文件:

      import cProfile, pstats, io
      from pstats import SortKey
      pr = cProfile.Profile()
      pr.enable()
      # ... do something ...
      pr.disable()
      s = io.StringIO()
      sortby = SortKey.CUMULATIVE
      ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
      ps.print_stats()
      print(s.getvalue())

   "Profile" 类也可作为上下文管理器使用 (仅在 "cProfile" 模块中支持。
   参见 上下文管理器类型):

      import cProfile

      with cProfile.Profile() as pr:
          # ... do something ...

      pr.print_stats()

   在 3.8 版更改: 添加了上下文管理器支持。

   enable()

      开始收集分析数据。仅在 "cProfile" 可用。

   disable()

      停止收集分析数据。仅在 "cProfile" 可用。

   create_stats()

      停止收集分析数据，并在内部将结果记录为当前 profile。

   print_stats(sort=-1)

      根据当前性能分析数据创建一个 "Stats" 对象并将结果打印到 stdout。

   dump_stats(filename)

      将当前profile 的结果写入 *filename* 。

   run(cmd)

      通过 "exec()" 对该命令进行性能分析。

   runctx(cmd, globals, locals)

      通过 "exec()" 并附带指定的全局和局部环境对该命令进行性能分析。

   runcall(func, *args, **kwargs)

      对 "func(*args, **kwargs)" 进行性能分析

请注意性能分析只有在被调用的命令/函数确实能返回时才可用。 如果解释器被
终结（例如在被调用的命令/函数执行期间通过 "sys.exit()" 调用）则将不会
打印性能分析结果。


"Stats" 类
==========

性能数据的分析是使用 "Stats" 类来完成的。

class pstats.Stats(*filenames or profile, stream=sys.stdout)

   这个类构造器会基于 *filename* (或文件名列表) 或者 "Profile" 实例创
   建一个“统计对象”。 输出将被打印到由 *stream* 所指定的流。

   上述构造器所选择的文件必须由相应版本的 "profile" 或 "cProfile" 来创
   建。 具体来说，*不会* 保证文件与此性能分析器的未来版本兼容，也不会
   保证与其他性能分析器，或运行于不同操作系统的同一性能分析器所产生的
   文件兼容。 如果提供了几个文件，则相同函数的所有统计数据将被聚合在一
   起，这样就可以在单个报告中同时考虑几个进程的总体情况。 如果额外的文
   件需要与现有 "Stats" 对象中的数据相结合，则可以使用 "add()" 方法。

   作为从一个文件读取性能分析数据的替代，可以使用 "cProfile.Profile"
   或 "profile.Profile" 对象作为性能分析数据源。

   "Stats" 对象有以下方法:

   strip_dirs()

      这个用于 "Stats" 类的方法会从文件名中去除所有前导路径信息。 它对
      于减少打印输出的大小以适应（接近） 80 列限制。 这个方法会修改对
      象，被去除的信息将会丢失。 在执行去除操作后，可以认为对象拥有的
      条目将使用“随机”顺序，就像它刚在对象初始化并加载之后一样。 如果
      "strip_dirs()" 导致两个函数名变得无法区分（它们位于相同文件名的
      相同行，并且具有相同的函数名），那么这两个条目的统计数据将被累积
      到单个条目中。

   add(*filenames)

      "Stats" 类的这个方法会将额外的性能分析信息累积到当前的性能分析对
      象中。 它的参数应当指向由相应版本的 "profile.run()" 或
      "cProfile.run()" 所创建的文件名。 相同名称（包括 file, line,
      name）函数的统计信息会自动累积到单个函数的统计信息。

   dump_stats(filename)

      Save the data loaded into the "Stats" object to a file named
      *filename*.  The file is created if it does not exist, and is
      overwritten if it already exists.  This is equivalent to the
      method of the same name on the "profile.Profile" and
      "cProfile.Profile" classes.

   sort_stats(*keys)

      This method modifies the "Stats" object by sorting it according
      to the supplied criteria.  The argument can be either a string
      or a SortKey enum identifying the basis of a sort (example:
      "'time'", "'name'", "SortKey.TIME" or "SortKey.NAME"). The
      SortKey enums argument have advantage over the string argument
      in that it is more robust and less error prone.

      When more than one key is provided, then additional keys are
      used as secondary criteria when there is equality in all keys
      selected before them.  For example, "sort_stats(SortKey.NAME,
      SortKey.FILE)" will sort all the entries according to their
      function name, and resolve all ties (identical function names)
      by sorting by file name.

      For the string argument, abbreviations can be used for any key
      names, as long as the abbreviation is unambiguous.

      The following are the valid string and SortKey:

      +--------------------+-----------------------+------------------------+
      | 有效字符串参数     | 有效枚举参数          | 含义                   |
      |====================|=======================|========================|
      | "'calls'"          | SortKey.CALLS         | 调用次数               |
      +--------------------+-----------------------+------------------------+
      | "'cumulative'"     | SortKey.CUMULATIVE    | 累积时间               |
      +--------------------+-----------------------+------------------------+
      | "'cumtime'"        | N/A                   | 累积时间               |
      +--------------------+-----------------------+------------------------+
      | "'file'"           | N/A                   | 文件名                 |
      +--------------------+-----------------------+------------------------+
      | "'filename'"       | SortKey.FILENAME      | 文件名                 |
      +--------------------+-----------------------+------------------------+
      | "'module'"         | N/A                   | 文件名                 |
      +--------------------+-----------------------+------------------------+
      | "'ncalls'"         | N/A                   | 调用次数               |
      +--------------------+-----------------------+------------------------+
      | "'pcalls'"         | SortKey.PCALLS        | 原始调用计数           |
      +--------------------+-----------------------+------------------------+
      | "'line'"           | SortKey.LINE          | 行号                   |
      +--------------------+-----------------------+------------------------+
      | "'name'"           | SortKey.NAME          | 函数名称               |
      +--------------------+-----------------------+------------------------+
      | "'nfl'"            | SortKey.NFL           | 名称/文件/行           |
      +--------------------+-----------------------+------------------------+
      | "'stdname'"        | SortKey.STDNAME       | 标准名称               |
      +--------------------+-----------------------+------------------------+
      | "'time'"           | SortKey.TIME          | 内部时间               |
      +--------------------+-----------------------+------------------------+
      | "'tottime'"        | N/A                   | 内部时间               |
      +--------------------+-----------------------+------------------------+

      Note that all sorts on statistics are in descending order
      (placing most time consuming items first), where as name, file,
      and line number searches are in ascending order (alphabetical).
      The subtle distinction between "SortKey.NFL" and
      "SortKey.STDNAME" is that the standard name is a sort of the
      name as printed, which means that the embedded line numbers get
      compared in an odd way.  For example, lines 3, 20, and 40 would
      (if the file names were the same) appear in the string order 20,
      3 and 40. In contrast, "SortKey.NFL" does a numeric compare of
      the line numbers. In fact, "sort_stats(SortKey.NFL)" is the same
      as "sort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE)".

      For backward-compatibility reasons, the numeric arguments "-1",
      "0", "1", and "2" are permitted.  They are interpreted as
      "'stdname'", "'calls'", "'time'", and "'cumulative'"
      respectively.  If this old style format (numeric) is used, only
      one sort key (the numeric key) will be used, and additional
      arguments will be silently ignored.

      3.7 新版功能: Added the SortKey enum.

   reverse_order()

      This method for the "Stats" class reverses the ordering of the
      basic list within the object.  Note that by default ascending vs
      descending order is properly selected based on the sort key of
      choice.

   print_stats(*restrictions)

      This method for the "Stats" class prints out a report as
      described in the "profile.run()" definition.

      The order of the printing is based on the last "sort_stats()"
      operation done on the object (subject to caveats in "add()" and
      "strip_dirs()").

      The arguments provided (if any) can be used to limit the list
      down to the significant entries.  Initially, the list is taken
      to be the complete set of profiled functions.  Each restriction
      is either an integer (to select a count of lines), or a decimal
      fraction between 0.0 and 1.0 inclusive (to select a percentage
      of lines), or a string that will interpreted as a regular
      expression (to pattern match the standard name that is printed).
      If several restrictions are provided, then they are applied
      sequentially. For example:

         print_stats(.1, 'foo:')

      would first limit the printing to first 10% of list, and then
      only print functions that were part of filename ".*foo:".  In
      contrast, the command:

         print_stats('foo:', .1)

      would limit the list to all functions having file names
      ".*foo:", and then proceed to only print the first 10% of them.

   print_callers(*restrictions)

      This method for the "Stats" class prints a list of all functions
      that called each function in the profiled database.  The
      ordering is identical to that provided by "print_stats()", and
      the definition of the restricting argument is also identical.
      Each caller is reported on its own line.  The format differs
      slightly depending on the profiler that produced the stats:

      * With "profile", a number is shown in parentheses after each
        caller to show how many times this specific call was made.
        For convenience, a second non-parenthesized number repeats the
        cumulative time spent in the function at the right.

      * With "cProfile", each caller is preceded by three numbers: the
        number of times this specific call was made, and the total and
        cumulative times spent in the current function while it was
        invoked by this specific caller.

   print_callees(*restrictions)

      This method for the "Stats" class prints a list of all function
      that were called by the indicated function.  Aside from this
      reversal of direction of calls (re: called vs was called by),
      the arguments and ordering are identical to the
      "print_callers()" method.


什么是确定性性能分析？
======================

*确定性性能分析* 旨在反映这样一个事实：即所有 *函数调用* 、 *函数返回*
和 *异常* 事件都被监控，并且对这些事件之间的间隔（在此期间用户的代码正
在执行）进行精确计时。相反，统计分析（不是由该模块完成）随机采样有效指
令指针，并推断时间花费在哪里。后一种技术传统上涉及较少的开销（因为代码
不需要检测），但只提供了时间花在哪里的相对指示。

在Python中，由于在执行过程中总有一个活动的解释器，因此执行确定性评测不
需要插入指令的代码。Python 自动为每个事件提供一个:dfn:*钩子* （可选回
调）。此外，Python 的解释特性往往会给执行增加太多开销，以至于在典型的
应用程序中，确定性分析往往只会增加很小的处理开销。结果是，确定性分析并
没有那么代价高昂，但是它提供了有关 Python 程序执行的大量运行时统计信息
。

调用计数统计信息可用于识别代码中的错误（意外计数），并识别可能的内联扩
展点（高频调用）。内部时间统计可用于识别应仔细优化的 "热循环" 。累积时
间统计可用于识别算法选择上的高级别错误。请注意，该分析器中对累积时间的
异常处理，允许直接比较算法的递归实现与迭代实现的统计信息。


局限性
======

一个限制是关于时间信息的准确性。确定性性能分析存在一个涉及精度的基本问
题。最明显的限制是，底层的 "时钟" 周期大约为0.001秒（通常）。因此，没
有什么测量会比底层时钟更精确。如果进行了足够的测量，那么 "误差" 将趋于
平均。不幸的是，删除第一个错误会导致第二个错误来源。

第二个问题是，从调度事件到分析器调用获取时间函数实际 *获取* 时钟状态，
这需要 "一段时间" 。类似地，从获取时钟值（然后保存）开始，直到再次执行
用户代码为止，退出分析器事件句柄时也存在一定的延迟。因此，多次调用单个
函数或调用多个函数通常会累积此错误。尽管这种方式的误差通常小于时钟的精
度（小于一个时钟周期），但它 *可以* 累积并变得非常可观。

与开销较低的 "cProfile" 相比， "profile" 的问题更为严重。出于这个原因
， "profile" 提供了一种针对指定平台的自我校准方法，以便可以在很大程度
上（平均地）消除此误差。  校准后，结果将更准确（在最小二乘意义上），但
它有时会产生负数（当调用计数异常低，且概率之神对您不利时：-）。因此 *
不要* 对产生的负数感到惊慌。它们应该只在你手工校准分析器的情况下才会出
现，实际上结果比没有校准的情况要好。


准确估量
========

"profile" 模块的 profiler 会从每个事件处理时间中减去一个常量，以补偿调
用 time 函数和存储结果的开销。默认情况下，常数为0。对于特定的平台，可
用以下程序获得更好修正常数（ 局限性 ）。

   import profile
   pr = profile.Profile()
   for i in range(5):
       print(pr.calibrate(10000))

The method executes the number of Python calls given by the argument,
directly and again under the profiler, measuring the time for both. It
then computes the hidden overhead per profiler event, and returns that
as a float.  For example, on a 1.8Ghz Intel Core i5 running Mac OS X,
and using Python's time.process_time() as the timer, the magical
number is about 4.04e-6.

The object of this exercise is to get a fairly consistent result. If
your computer is *very* fast, or your timer function has poor
resolution, you might have to pass 100000, or even 1000000, to get
consistent results.

当你有一个一致的答案时，有三种方法可以使用：

   import profile

   # 1. Apply computed bias to all Profile instances created hereafter.
   profile.Profile.bias = your_computed_bias

   # 2. Apply computed bias to a specific Profile instance.
   pr = profile.Profile()
   pr.bias = your_computed_bias

   # 3. Specify computed bias in instance constructor.
   pr = profile.Profile(bias=your_computed_bias)

If you have a choice, you are better off choosing a smaller constant,
and then your results will "less often" show up as negative in profile
statistics.


使用自定义计时器
================

If you want to change how current time is determined (for example, to
force use of wall-clock time or elapsed process time), pass the timing
function you want to the "Profile" class constructor:

   pr = profile.Profile(your_time_func)

The resulting profiler will then call "your_time_func". Depending on
whether you are using "profile.Profile" or "cProfile.Profile",
"your_time_func"'s return value will be interpreted differently:

"profile.Profile"
   "your_time_func" should return a single number, or a list of
   numbers whose sum is the current time (like what "os.times()"
   returns).  If the function returns a single time number, or the
   list of returned numbers has length 2, then you will get an
   especially fast version of the dispatch routine.

   Be warned that you should calibrate the profiler class for the
   timer function that you choose (see 准确估量).  For most machines,
   a timer that returns a lone integer value will provide the best
   results in terms of low overhead during profiling.  ("os.times()"
   is *pretty* bad, as it returns a tuple of floating point values).
   If you want to substitute a better timer in the cleanest fashion,
   derive a class and hardwire a replacement dispatch method that best
   handles your timer call, along with the appropriate calibration
   constant.

"cProfile.Profile"
   "your_time_func" should return a single number.  If it returns
   integers, you can also invoke the class constructor with a second
   argument specifying the real duration of one unit of time.  For
   example, if "your_integer_time_func" returns times measured in
   thousands of seconds, you would construct the "Profile" instance as
   follows:

      pr = cProfile.Profile(your_integer_time_func, 0.001)

   As the "cProfile.Profile" class cannot be calibrated, custom timer
   functions should be used with care and should be as fast as
   possible.  For the best results with a custom timer, it might be
   necessary to hard-code it in the C source of the internal "_lsprof"
   module.

Python 3.3 adds several new functions in "time" that can be used to
make precise measurements of process or wall-clock time. For example,
see "time.perf_counter()".
