Python 剖分析器

源代码: Lib/profile.py and Lib/pstats.py


剖分析器介绍

cProfile and profile 提供 确定性剖分析 为 Python 程序。 profile is a set of statistics that describes how often and for how long various parts of the program executed. These statistics can be formatted into reports via the pstats 模块。

The Python standard library provides two different implementations of the same profiling interface:

  1. cProfile is recommended for most users; it’s a C extension with reasonable overhead that makes it suitable for profiling long-running programs. Based on lsprof , contributed by Brett Rosen and Ted Czotter.

  2. profile , a pure Python module whose interface is imitated by cProfile , but which adds significant overhead to profiled programs. If you’re trying to extend the profiler in some way, the task might be easier with this module. Originally designed and written by Jim Roskind.

注意

The profiler modules are designed to provide an execution profile for a given program, not for benchmarking purposes (for that, there is timeit for reasonably accurate results). This particularly applies to benchmarking Python code against C code: the profilers introduce overhead for Python code, but not for C-level functions, and so the C code would seem faster than any Python one.

即时用户手册

This section is provided for users that “don’t want to read the manual.” It provides a very brief overview, and allows a user to rapidly perform profiling on an existing application.

To profile a function that takes a single argument, you can do:

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