Debian Codegraph @

pyinstrument/frame_ops.py

raw symbols SCIP
1 from __future__ import annotations
2
3 from typing import List, Sequence, Tuple
4
5 from pyinstrument.frame import (
6 DUMMY_ROOT_FRAME_IDENTIFIER,
7 SELF_TIME_FRAME_IDENTIFIER,
8 Frame,
9 FrameContext,
10 )
11 from pyinstrument.frame_info import frame_info_get_identifier
12 from pyinstrument.typing import LiteralStr, assert_never
13
14 # pyright: strict
15
16
17 FrameRecordType = Tuple[List[str], float]
18
19
20 class IdentifierDoesntMatchException(ValueError):
21 pass
22
23
24 def build_frame_tree(
25 frame_records: Sequence[FrameRecordType], context: FrameContext
26 ) -> Frame | None:
27 if len(frame_records) == 0:
28 return None
29
30 root_frame = Frame(identifier_or_frame_info=DUMMY_ROOT_FRAME_IDENTIFIER, context=context)
31
32 # put the root frame at the bottom of the stack
33 frame_stack: list[Frame] = [root_frame]
34
35 for frame_info_stack, time in frame_records:
36 stack_depth = 0
37 root_frame.record_time_from_frame_info(DUMMY_ROOT_FRAME_IDENTIFIER, time)
38
39 for stack_depth, frame_info in enumerate(frame_info_stack, start=1):
40 frame_identifier = frame_info_get_identifier(frame_info)
41 try:
42 frame = frame_stack[stack_depth]
43 if frame.identifier != frame_identifier:
44 # trim any frames after and including this one, and make a new frame
45 del frame_stack[stack_depth:]
46 raise IdentifierDoesntMatchException()
47 except (IndexError, IdentifierDoesntMatchException):
48 # create a new frame
49 parent = frame_stack[stack_depth - 1]
50 frame = Frame(identifier_or_frame_info=frame_info)
51 parent.add_child(frame)
52
53 assert len(frame_stack) == stack_depth
54 frame_stack.append(frame)
55
56 frame.record_time_from_frame_info(frame_info=frame_info, time=time)
57
58 # trim any extra frames
59 del frame_stack[stack_depth + 1 :]
60
61 final_frame = frame_stack[-1]
62
63 if not final_frame.is_synthetic_leaf:
64 # record the self-time
65 final_frame.add_child(
66 Frame(identifier_or_frame_info=SELF_TIME_FRAME_IDENTIFIER, time=time)
67 )
68
69 if len(root_frame.children) == 1:
70 root_frame = root_frame.children[0]
71 root_frame.remove_from_parent()
72
73 return root_frame
74
75
76 def delete_frame_from_tree(
77 frame: Frame, replace_with: LiteralStr["children", "self_time", "nothing"]
78 ):
79 """
80 Delete a frame from the tree.
81
82 :param frame: the frame to delete
83 :param replace_with: what to replace the frame with - `children` replaces
84 the frame with its children, `self_time` replaces the frame with a
85 self-time frame, and `nothing` deletes the frame, absorbing the time
86 into the parent.
87 """
88 parent = frame.parent
89 if parent is None:
90 raise ValueError("Cannot delete the root frame")
91
92 if replace_with == "children":
93 parent.add_children(frame.children, after=frame)
94 elif replace_with == "self_time":
95 parent.add_child(
96 Frame(identifier_or_frame_info=SELF_TIME_FRAME_IDENTIFIER, time=frame.time),
97 after=frame,
98 )
99 elif replace_with == "nothing":
100 parent.absorbed_time += frame.time
101 else:
102 assert_never(replace_with)
103
104 parent.absorbed_time += frame.absorbed_time
105
106 frame.remove_from_parent()
107 # in this call, recursive is true, even when replace_with is 'children'.
108 # When replace_with is 'self_time' or 'nothing', that's what we want. But
109 # when it's 'children', by now, the children have been removed and added
110 # to the parent, so recursive is irrelevant.
111 remove_frame_from_groups(frame, recursive=True)
112
113
114 def combine_frames(frame: Frame, into: Frame):
115 """
116 Combine two frames into one. The frames must have the same parent.
117
118 :param frame: the frame to remove
119 :param into: the frame to combine into
120 """
121 assert frame.parent is into.parent
122
123 into.absorbed_time += frame.absorbed_time
124 into.time += frame.time
125
126 for attribute, time in frame.attributes.items():
127 try:
128 into.attributes[attribute] += time
129 except KeyError:
130 into.attributes[attribute] = time
131
132 into.add_children(frame.children)
133 frame.remove_from_parent()
134 remove_frame_from_groups(frame, recursive=False)
135
136
137 def remove_frame_from_groups(frame: Frame, recursive: bool):
138 """
139 Removes frame from any groups that it is a member of. Should be used when
140 removing a frame from a tree, so groups don't keep references to removed
141 frames.
142 """
143 if recursive and frame.children:
144 for child in frame.children:
145 remove_frame_from_groups(child, recursive=True)
146
147 if frame.group:
148 group = frame.group
149 group.remove_frame(frame)
150
151 if len(group.frames) == 1:
152 # a group with only one frame is meaningless, we'll remove it
153 # entirely.
154 group.remove_frame(group.frames[0])