# 十六、基准测试、性能分析和追踪

在对 CPython 进行更改时，你需要验证你的更改不会对性能产生显著的负面影响。你甚至可能想要改变 CPython 以提高性能。

你将在本章中学到一些性能分析的方法：

1. 使用 `timeit` 模块将一些简单的 Python 语句执行数千次，以确定执行速度的中间值；
2. 运行 `pyperformance` （一个 Python 基准测试套件）来比较多个 Python 版本；
3. 使用 `cProfile` 分析帧的执行时间；
4. 使用探针（`probe`）分析 CPython 的执行性能。

究竟选择哪种方案的取决于任务的类型：

* \*\*基准测试（benchmark）\*\*将输出固定代码片段运行时间的平均值或中间值，以便你去比较多个 Python 运行时；
* \*\*性能分析器（profiler）\*\*将生成一个带有执行时间的调用图，这样你就可以了解哪个函数的执行速度最慢。

性能分析器可以在 C 层级或 Python 层级使用。如果你正在分析使用 Python 编写的函数、模块或脚本，那么你需要使用 Python 性能分析器。如果你正在分析 CPython 中的 C 扩展模块或对 C 代码的修改，那么你需要使用 C 的性能分析器或组合使用 C 和 Python 的性能分析器。

以下是对一些可用工具的概括说明：

| 工具              | 类别      | 层级     | 支持的操作系统      |
| --------------- | ------- | ------ | ------------ |
| `timeit`        | 基准测试    | Python | 所有操作系统       |
| `pyperformance` | 基准测试    | Python | 所有操作系统       |
| `cProfile`      | 性能分析    | Python | 所有操作系统       |
| `DTrace`        | 追踪/性能分析 | C      | Linux, macOS |

**重要：**

在运行任何基准测试之前，最好关闭计算机上的所有应用程序，以便 CPU 可以专门用于基准测试。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hai-shi.gitbook.io/cpython-internals/16-performance-analysis.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
