对 Perf Maps 的支持¶
在受支持的平台上(Linux 和 macOS),运行时可以利用 perf map 文件 来使 Python 函数对于外部性能分析工具可见(例如 perf 或 samply 等)。 正在运行的进程可以在 /tmp 目录中创建一个文件,其中包含可将部分可执行代码映射到特定名称的条目。 本接口的描述参见 Linux Perf 工具的文件。
在 Python 中,这些辅助 API 可供依赖于动态生成机器码的库和特性使用。
请注意这些 API 并不要求持有已附加的线程状态 attached thread state。
-
int PyUnstable_PerfMapState_Init(void)¶
- 这是 不稳定 API。它可能在次要版本中不经警告地被更改。
打开
/tmp/perf-$pid.map文件,除非它已经被打开,并创建一个锁来确保线程安全地写入该文件(如果写入是通过PyUnstable_WritePerfMapEntry()执行的)。通常,没有必要显式地调用此函数;只需使用PyUnstable_WritePerfMapEntry(),它将在第一次调用时初始化状态。成功时返回
0,创建/打开 perf map 文件失败时返回-1,或者创建锁失败时返回-2。可检查errno获取有关失败原因的更多信息。
-
int PyUnstable_WritePerfMapEntry(const void *code_addr, size_t code_size, const char *entry_name)¶
- 这是 不稳定 API。它可能在次要版本中不经警告地被更改。
向
/tmp/perf-$pid.map文件写入一个单独条目。此函数是线程安全的。下面显示了一个示例条目:# 地址 大小 名称 7f3529fcf759 b py::bar:/run/t.py
将在写入条目之前调用
PyUnstable_PerfMapState_Init(),如果 perf map 文件尚未打开。成功时返回0,或者在失败时返回与PyUnstable_PerfMapState_Init()相同的错误代码。
-
void PyUnstable_PerfMapState_Fini(void)¶
- 这是 不稳定 API。它可能在次要版本中不经警告地被更改。
关闭
PyUnstable_PerfMapState_Init()所打开的 perf map 文件。 此函数会在解释器关闭期间由运行时本身调用。通常,应该没有理由显式地调用此函数,除了处理特殊场景例如分叉操作。
-
int PyUnstable_CopyPerfMapFile(const char *parent_filename)¶
- 这是 不稳定 API。它可能在次要版本中不经警告地被更改。
Open the
/tmp/perf-$pid.mapfile and append the content of parent_filename to it.This function is available on all platforms but only generates output on platforms that support perf maps (currently only Linux). On other platforms, it does nothing.
Added in version 3.13.
-
int PyUnstable_PerfTrampoline_CompileCode(PyCodeObject *code)¶
- 这是 不稳定 API。它可能在次要版本中不经警告地被更改。
Compile the given code object using the current perf trampoline.
The "current" trampoline is the one set by the runtime or the most recent
PyUnstable_PerfTrampoline_SetPersistAfterFork()call.If no trampoline is set, falls back to normal compilation (no perf map entry).
- 参数:
code -- 要编译的代码对象。
- 返回:
成功时返回 0,失败时返回 -1。
Added in version 3.13.
-
int PyUnstable_PerfTrampoline_SetPersistAfterFork(int enable)¶
- 这是 不稳定 API。它可能在次要版本中不经警告地被更改。
Set whether the perf trampoline should persist after a fork.
If
enableis true (non-zero): perf map file remains open/valid post-fork. Child process inherits all existing perf map entries.If
enableis false (zero): perf map closes post-fork. Child process gets empty perf map.
默认值: false (分叉时清空)。
- 参数:
enable -- 1 为启用, 0 为禁用。
- 返回:
成功时返回 0,失败时返回 -1。
Added in version 3.13.