對 Perf Map 的支援

On supported platforms (Linux and macOS), the runtime can take advantage of perf map files to make Python functions visible to an external profiling tool (such as perf or samply). A running process may create a file in the /tmp directory, which contains entries that can map a section of executable code to a name. This interface is described in the documentation of the Linux Perf tool.

在 Python 中,這些輔助 API 可以被依賴於運行期間 (on the fly) 產生機器碼的函式庫和功能所使用。

請注意,這些 API 不需要持有 attached thread state

int PyUnstable_PerfMapState_Init(void)
這是 不穩定 API,它可能在小版本發布中沒有任何警告地被變更。

打開 /tmp/perf-$pid.map 檔案,除非它已經打開,並建立一個鎖以確保執行緒安全地 (thread-safe) 寫入該檔案(前提是寫入是透過 PyUnstable_WritePerfMapEntry() 完成的)。通常不需要明確地呼叫它;只需使用 PyUnstable_WritePerfMapEntry() 它就會在首次呼叫時初始化狀態。

建立/打開 perf map 檔案成功時回傳 0,失敗時回傳 -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

如果尚未開啟 perf map 檔案,將在寫入條目之前呼叫 PyUnstable_PerfMapState_Init()。成功時回傳 0,失敗時回傳與 PyUnstable_PerfMapState_Init() 失敗時相同的錯誤碼。

void PyUnstable_PerfMapState_Fini(void)
這是 不穩定 API,它可能在小版本發布中沒有任何警告地被變更。

關閉由 PyUnstable_PerfMapState_Init() 開啟的 perf map 檔案,這是在直譯器關閉期間由 runtime 本身呼叫的。一般來說,除了處理 forking 等特定場景外,不應該明確地呼叫它。

int PyUnstable_CopyPerfMapFile(const char *parent_filename)
這是 不穩定 API,它可能在小版本發布中沒有任何警告地被變更。

Open the /tmp/perf-$pid.map file 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.

在 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 -- The code object to compile.

回傳:

0 on success, -1 on failure.

在 3.13 版被加入.

int PyUnstable_PerfTrampoline_SetPersistAfterFork(int enable)
這是 不穩定 API,它可能在小版本發布中沒有任何警告地被變更。

Set whether the perf trampoline should persist after a fork.

  • If enable is true (non-zero): perf map file remains open/valid post-fork. Child process inherits all existing perf map entries.

  • If enable is false (zero): perf map closes post-fork. Child process gets empty perf map.

Default: false (clears on fork).

參數:
  • enable -- 1 to enable, 0 to disable.

回傳:

0 on success, -1 on failure.

在 3.13 版被加入.