Debian Codegraph @

pyinstrument/processors.py

raw symbols SCIP
1 """
2 Processors are functions that take a Frame object, and mutate the tree to perform some task.
3
4 They can mutate the tree in-place, but also can change the root frame, they should always be
5 called like::
6
7 frame = processor(frame, options=...)
8 """
9
10 from __future__ import annotations
11
12 import re
13 from typing import Any, Callable, Dict, Union
14
15 from pyinstrument.frame import SELF_TIME_FRAME_IDENTIFIER, Frame, FrameGroup
16 from pyinstrument.frame_ops import combine_frames, delete_frame_from_tree
17
18 # pyright: strict
19
20
21 ProcessorType = Callable[..., Union[Frame, None]]
22 ProcessorOptions = Dict[str, Any]
23
24
25 def remove_importlib(frame: Frame | None, options: ProcessorOptions) -> Frame | None:
26 """
27 Removes ``<frozen importlib._bootstrap`` frames that clutter the output.
28 """
29 if frame is None:
30 return None
31
32 for child in frame.children:
33 remove_importlib(child, options=options)
34
35 if child.file_path and "<frozen importlib._bootstrap" in child.file_path:
36 delete_frame_from_tree(child, replace_with="children")
37
38 return frame
39
40
41 def remove_tracebackhide(frame: Frame | None, options: ProcessorOptions) -> Frame | None:
42 """
43 Removes frames that have set a local `__tracebackhide__` (e.g.
44 `__tracebackhide__ = True`), to hide them from the output.
45 """
46 if frame is None:
47 return None
48
49 for child in frame.children:
50 remove_tracebackhide(child, options=options)
51
52 if child.has_tracebackhide:
53 # remove this node, moving the self_time and children up to the parent
54 delete_frame_from_tree(child, replace_with="children")
55
56 return frame
57
58
59 def aggregate_repeated_calls(frame: Frame | None, options: ProcessorOptions) -> Frame | None:
60 """
61 Converts a timeline into a time-aggregate summary.
62
63 Adds together calls along the same call stack, so that repeated calls appear as the same
64 frame. Removes time-linearity - frames are sorted according to total time spent.
65
66 Useful for outputs that display a summary of execution (e.g. text and html outputs)
67 """
68 if frame is None:
69 return None
70
71 children_by_identifier: dict[str, Frame] = {}
72
73 # iterate over a copy of the children since it's going to mutate while we're iterating
74 for child in frame.children:
75 if child.identifier in children_by_identifier:
76 aggregate_frame = children_by_identifier[child.identifier]
77
78 # combine child into aggregate frame, removing it from the tree
79 combine_frames(child, into=aggregate_frame)
80 else:
81 # never seen this identifier before. It becomes the aggregate frame.
82 children_by_identifier[child.identifier] = child
83
84 # recurse into the children
85 for child in frame.children:
86 aggregate_repeated_calls(child, options=options)
87
88 # sort the children by time
89 # we use the internal _children list, because we need to mutate it
90 frame._children.sort(key=lambda c: c.time, reverse=True) # type: ignore # noqa
91
92 return frame
93
94
95 def group_library_frames_processor(frame: Frame | None, options: ProcessorOptions) -> Frame | None:
96 """
97 Groups frames that should be hidden into :class:`FrameGroup` objects,
98 according to ``hide_regex`` and ``show_regex`` in the options dict, as
99 applied to the file path of the source code of the frame. If both match,
100 'show' has precedence.
101 Options:
102
103 ``hide_regex``
104 regular expression, which if matches the file path, hides the frame in a
105 frame group.
106
107 ``show_regex``
108 regular expression, which if matches the file path, ensures the frame is
109 not hidden
110
111 Single frames are not grouped, there must be at least two frames in a
112 group.
113 """
114 if frame is None:
115 return None
116
117 hide_regex: str | None = options.get("hide_regex")
118 show_regex: str | None = options.get("show_regex")
119
120 def should_be_hidden(frame: Frame):
121 frame_file_path = frame.file_path or ""
122
123 should_show = (show_regex is not None) and re.match(show_regex, frame_file_path)
124 should_hide = (hide_regex is not None) and re.match(hide_regex, frame_file_path)
125
126 # check for explicit user show/hide rules. 'show' has precedence.
127 if should_show:
128 return False
129 if should_hide:
130 return True
131
132 return not frame.is_application_code
133
134 def add_frames_to_group(frame: Frame, group: FrameGroup):
135 group.add_frame(frame)
136 for child in frame.children:
137 if should_be_hidden(child):
138 add_frames_to_group(child, group)
139
140 for child in frame.children:
141 if not child.group and (
142 should_be_hidden(child) and any(should_be_hidden(cc) for cc in child.children)
143 ):
144 group = FrameGroup(child)
145 add_frames_to_group(child, group)
146
147 group_library_frames_processor(child, options=options)
148
149 return frame
150
151
152 def merge_consecutive_self_time(
153 frame: Frame | None, options: ProcessorOptions, recursive: bool = True
154 ) -> Frame | None:
155 """
156 Combines consecutive 'self time' frames.
157 """
158 if frame is None:
159 return None
160
161 previous_self_time_frame = None
162
163 for child in frame.children:
164 if child.identifier == SELF_TIME_FRAME_IDENTIFIER:
165 if previous_self_time_frame:
166 # merge
167 previous_self_time_frame.time += child.time
168 child.remove_from_parent()
169 else:
170 # keep a reference, maybe it'll be added to on the next loop
171 previous_self_time_frame = child
172 else:
173 previous_self_time_frame = None
174
175 if recursive:
176 for child in frame.children:
177 merge_consecutive_self_time(child, options=options, recursive=True)
178
179 return frame
180
181
182 def remove_unnecessary_self_time_nodes(
183 frame: Frame | None, options: ProcessorOptions
184 ) -> Frame | None:
185 """
186 When a frame has only one child, and that is a self-time frame, remove
187 that node and move the time to parent, since it's unnecessary - it
188 clutters the output and offers no additional information.
189 """
190 if frame is None:
191 return None
192
193 if len(frame.children) == 1 and frame.children[0].identifier == SELF_TIME_FRAME_IDENTIFIER:
194 delete_frame_from_tree(frame.children[0], replace_with="nothing")
195
196 for child in frame.children:
197 remove_unnecessary_self_time_nodes(child, options=options)
198
199 return frame
200
201
202 def remove_irrelevant_nodes(
203 frame: Frame | None, options: ProcessorOptions, total_time: float | None = None
204 ) -> Frame | None:
205 """
206 Remove nodes that represent less than e.g. 1% of the output. Options:
207
208 ``filter_threshold``
209 sets the minimum duration of a frame to be included in the output.
210 Default: 0.01.
211 """
212 if frame is None:
213 return None
214
215 if total_time is None:
216 total_time = frame.time
217
218 # prevent divide by zero
219 if total_time <= 0:
220 total_time = 1e-44
221
222 filter_threshold = options.get("filter_threshold", 0.01)
223
224 for child in frame.children:
225 proportion_of_total = child.time / total_time
226
227 if proportion_of_total < filter_threshold:
228 delete_frame_from_tree(child, replace_with="nothing")
229
230 for child in frame.children:
231 remove_irrelevant_nodes(child, options=options, total_time=total_time)
232
233 return frame
234
235
236 # pylint: disable=W0613
237 def remove_first_pyinstrument_frames_processor(
238 frame: Frame | None, options: ProcessorOptions
239 ) -> Frame | None:
240 """
241 The first few frames when using the command line are the __main__ of
242 pyinstrument, the eval, and the 'runpy' module. I want to remove that from
243 the output.
244 """
245 if frame is None:
246 return None
247
248 # the initial pyinstrument frame
249 def is_initial_pyinstrument_frame(frame: Frame):
250 return (
251 frame.file_path is not None
252 and re.match(r".*pyinstrument[/\\]__main__.py", frame.file_path)
253 and len(frame.children) > 0
254 )
255
256 def is_exec_frame(frame: Frame):
257 return (
258 frame.proportion_of_parent > 0.8
259 and frame.file_path is not None
260 and "<string>" in frame.file_path
261 and len(frame.children) > 0
262 )
263
264 def is_runpy_frame(frame: Frame):
265 return (
266 frame.proportion_of_parent > 0.8
267 and frame.file_path is not None
268 and (re.match(r".*runpy.py", frame.file_path) or "<frozen runpy>" in frame.file_path)
269 and len(frame.children) > 0
270 )
271
272 result = frame
273
274 if not is_initial_pyinstrument_frame(result):
275 return frame
276
277 result = result.children[0]
278
279 if not is_exec_frame(result):
280 return frame
281
282 result = result.children[0]
283
284 # at this point we know we've matched the first few frames of a command
285 # line invocation. We'll trim some runpy frames and return.
286
287 while is_runpy_frame(result):
288 result = result.children[0]
289
290 # remove this frame from the parent to make it the new root frame
291 result.remove_from_parent()
292
293 return result