Debian Codegraph @

Doc/howto/perf_profiling.rst

raw
1 .. highlight:: shell-session
2
3 .. _perf_profiling:
4
5 ==============================================
6 Python support for the Linux ``perf`` profiler
7 ==============================================
8
9 :author: Pablo Galindo
10
11 `The Linux perf profiler <https://perf.wiki.kernel.org>`_
12 is a very powerful tool that allows you to profile and obtain
13 information about the performance of your application.
14 ``perf`` also has a very vibrant ecosystem of tools
15 that aid with the analysis of the data that it produces.
16
17 The main problem with using the ``perf`` profiler with Python applications is that
18 ``perf`` only gets information about native symbols, that is, the names of
19 functions and procedures written in C. This means that the names and file names
20 of Python functions in your code will not appear in the output of ``perf``.
21
22 Since Python 3.12, the interpreter can run in a special mode that allows Python
23 functions to appear in the output of the ``perf`` profiler. When this mode is
24 enabled, the interpreter will interpose a small piece of code compiled on the
25 fly before the execution of every Python function and it will teach ``perf`` the
26 relationship between this piece of code and the associated Python function using
27 :doc:`perf map files <../c-api/perfmaps>`.
28
29 .. note::
30
31 Support for the ``perf`` profiler is currently only available for Linux on
32 select architectures. Check the output of the ``configure`` build step or
33 check the output of ``python -m sysconfig | grep HAVE_PERF_TRAMPOLINE``
34 to see if your system is supported.
35
36 For example, consider the following script:
37
38 .. code-block:: python
39
40 def foo(n):
41 result = 0
42 for _ in range(n):
43 result += 1
44 return result
45
46 def bar(n):
47 foo(n)
48
49 def baz(n):
50 bar(n)
51
52 if __name__ == "__main__":
53 baz(1000000)
54
55 We can run ``perf`` to sample CPU stack traces at 9999 hertz::
56
57 $ perf record -F 9999 -g -o perf.data python my_script.py
58
59 Then we can use ``perf report`` to analyze the data:
60
61 .. code-block:: shell-session
62
63 $ perf report --stdio -n -g
64
65 # Children Self Samples Command Shared Object Symbol
66 # ........ ........ ............ .......... .................. ..........................................
67 #
68 91.08% 0.00% 0 python.exe python.exe [.] _start
69 |
70 ---_start
71 |
72 --90.71%--__libc_start_main
73 Py_BytesMain
74 |
75 |--56.88%--pymain_run_python.constprop.0
76 | |
77 | |--56.13%--_PyRun_AnyFileObject
78 | | _PyRun_SimpleFileObject
79 | | |
80 | | |--55.02%--run_mod
81 | | | |
82 | | | --54.65%--PyEval_EvalCode
83 | | | _PyEval_EvalFrameDefault
84 | | | PyObject_Vectorcall
85 | | | _PyEval_Vector
86 | | | _PyEval_EvalFrameDefault
87 | | | PyObject_Vectorcall
88 | | | _PyEval_Vector
89 | | | _PyEval_EvalFrameDefault
90 | | | PyObject_Vectorcall
91 | | | _PyEval_Vector
92 | | | |
93 | | | |--51.67%--_PyEval_EvalFrameDefault
94 | | | | |
95 | | | | |--11.52%--_PyLong_Add
96 | | | | | |
97 | | | | | |--2.97%--_PyObject_Malloc
98 ...
99
100 As you can see, the Python functions are not shown in the output, only ``_PyEval_EvalFrameDefault``
101 (the function that evaluates the Python bytecode) shows up. Unfortunately that's not very useful because all Python
102 functions use the same C function to evaluate bytecode so we cannot know which Python function corresponds to which
103 bytecode-evaluating function.
104
105 Instead, if we run the same experiment with ``perf`` support enabled we get:
106
107 .. code-block:: shell-session
108
109 $ perf report --stdio -n -g
110
111 # Children Self Samples Command Shared Object Symbol
112 # ........ ........ ............ .......... .................. .....................................................................
113 #
114 90.58% 0.36% 1 python.exe python.exe [.] _start
115 |
116 ---_start
117 |
118 --89.86%--__libc_start_main
119 Py_BytesMain
120 |
121 |--55.43%--pymain_run_python.constprop.0
122 | |
123 | |--54.71%--_PyRun_AnyFileObject
124 | | _PyRun_SimpleFileObject
125 | | |
126 | | |--53.62%--run_mod
127 | | | |
128 | | | --53.26%--PyEval_EvalCode
129 | | | py::<module>:/src/script.py
130 | | | _PyEval_EvalFrameDefault
131 | | | PyObject_Vectorcall
132 | | | _PyEval_Vector
133 | | | py::baz:/src/script.py
134 | | | _PyEval_EvalFrameDefault
135 | | | PyObject_Vectorcall
136 | | | _PyEval_Vector
137 | | | py::bar:/src/script.py
138 | | | _PyEval_EvalFrameDefault
139 | | | PyObject_Vectorcall
140 | | | _PyEval_Vector
141 | | | py::foo:/src/script.py
142 | | | |
143 | | | |--51.81%--_PyEval_EvalFrameDefault
144 | | | | |
145 | | | | |--13.77%--_PyLong_Add
146 | | | | | |
147 | | | | | |--3.26%--_PyObject_Malloc
148
149
150
151 How to enable ``perf`` profiling support
152 ----------------------------------------
153
154 ``perf`` profiling support can be enabled either from the start using
155 the environment variable :envvar:`PYTHONPERFSUPPORT` or the
156 :option:`-X perf <-X>` option,
157 or dynamically using :func:`sys.activate_stack_trampoline` and
158 :func:`sys.deactivate_stack_trampoline`.
159
160 The :mod:`!sys` functions take precedence over the :option:`!-X` option,
161 the :option:`!-X` option takes precedence over the environment variable.
162
163 Example, using the environment variable::
164
165 $ PYTHONPERFSUPPORT=1 perf record -F 9999 -g -o perf.data python my_script.py
166 $ perf report -g -i perf.data
167
168 Example, using the :option:`!-X` option::
169
170 $ perf record -F 9999 -g -o perf.data python -X perf my_script.py
171 $ perf report -g -i perf.data
172
173 Example, using the :mod:`sys` APIs in file :file:`example.py`:
174
175 .. code-block:: python
176
177 import sys
178
179 sys.activate_stack_trampoline("perf")
180 do_profiled_stuff()
181 sys.deactivate_stack_trampoline()
182
183 non_profiled_stuff()
184
185 ...then::
186
187 $ perf record -F 9999 -g -o perf.data python ./example.py
188 $ perf report -g -i perf.data
189
190
191 How to obtain the best results
192 ------------------------------
193
194 For best results, Python should be compiled with
195 ``CFLAGS="-fno-omit-frame-pointer -mno-omit-leaf-frame-pointer"`` as this allows
196 profilers to unwind using only the frame pointer and not on DWARF debug
197 information. This is because as the code that is interposed to allow ``perf``
198 support is dynamically generated it doesn't have any DWARF debugging information
199 available.
200
201 You can check if your system has been compiled with this flag by running::
202
203 $ python -m sysconfig | grep 'no-omit-frame-pointer'
204
205 If you don't see any output it means that your interpreter has not been compiled with
206 frame pointers and therefore it may not be able to show Python functions in the output
207 of ``perf``.
208
209
210 How to work without frame pointers
211 ----------------------------------
212
213 If you are working with a Python interpreter that has been compiled without
214 frame pointers, you can still use the ``perf`` profiler, but the overhead will be
215 a bit higher because Python needs to generate unwinding information for every
216 Python function call on the fly. Additionally, ``perf`` will take more time to
217 process the data because it will need to use the DWARF debugging information to
218 unwind the stack and this is a slow process.
219
220 To enable this mode, you can use the environment variable
221 :envvar:`PYTHON_PERF_JIT_SUPPORT` or the :option:`-X perf_jit <-X>` option,
222 which will enable the JIT mode for the ``perf`` profiler.
223
224 .. note::
225
226 Due to a bug in the ``perf`` tool, only ``perf`` versions higher than v6.8
227 will work with the JIT mode. The fix was also backported to the v6.7.2
228 version of the tool.
229
230 Note that when checking the version of the ``perf`` tool (which can be done
231 by running ``perf version``) you must take into account that some distros
232 add some custom version numbers including a ``-`` character. This means
233 that ``perf 6.7-3`` is not necessarily ``perf 6.7.3``.
234
235 When using the perf JIT mode, you need an extra step before you can run ``perf
236 report``. You need to call the ``perf inject`` command to inject the JIT
237 information into the ``perf.data`` file.::
238
239 $ perf record -F 9999 -g -k 1 --call-graph dwarf -o perf.data python -Xperf_jit my_script.py
240 $ perf inject -i perf.data --jit --output perf.jit.data
241 $ perf report -g -i perf.jit.data
242
243 or using the environment variable::
244
245 $ PYTHON_PERF_JIT_SUPPORT=1 perf record -F 9999 -g --call-graph dwarf -o perf.data python my_script.py
246 $ perf inject -i perf.data --jit --output perf.jit.data
247 $ perf report -g -i perf.jit.data
248
249 ``perf inject --jit`` command will read ``perf.data``,
250 automatically pick up the perf dump file that Python creates (in
251 ``/tmp/perf-$PID.dump``), and then create ``perf.jit.data`` which merges all the
252 JIT information together. It should also create a lot of ``jitted-XXXX-N.so``
253 files in the current directory which are ELF images for all the JIT trampolines
254 that were created by Python.
255
256 .. warning::
257 When using ``--call-graph dwarf``, the ``perf`` tool will take
258 snapshots of the stack of the process being profiled and save the
259 information in the ``perf.data`` file. By default, the size of the stack dump
260 is 8192 bytes, but you can change the size by passing it after
261 a comma like ``--call-graph dwarf,16384``.
262
263 The size of the stack dump is important because if the size is too small
264 ``perf`` will not be able to unwind the stack and the output will be
265 incomplete. On the other hand, if the size is too big, then ``perf`` won't
266 be able to sample the process as frequently as it would like as the overhead
267 will be higher.
268
269 The stack size is particularly important when profiling Python code compiled
270 with low optimization levels (like ``-O0``), as these builds tend to have
271 larger stack frames. If you are compiling Python with ``-O0`` and not seeing
272 Python functions in your profiling output, try increasing the stack dump
273 size to 65528 bytes (the maximum)::
274
275 $ perf record -F 9999 -g -k 1 --call-graph dwarf,65528 -o perf.data python -Xperf_jit my_script.py
276
277 Different compilation flags can significantly impact stack sizes:
278
279 - Builds with ``-O0`` typically have much larger stack frames than those with ``-O1`` or higher
280 - Adding optimizations (``-O1``, ``-O2``, etc.) typically reduces stack size
281 - Frame pointers (``-fno-omit-frame-pointer``) generally provide more reliable stack unwinding