Debian Codegraph @

pyinstrument/renderers/speedscope.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import json
4 import time
5 from dataclasses import dataclass
6 from enum import Enum
7 from typing import Any, Dict, Union
8
9 from pyinstrument import processors
10 from pyinstrument.frame import Frame
11 from pyinstrument.renderers.base import FrameRenderer, ProcessorList
12 from pyinstrument.session import Session
13
14 # pyright: strict
15
16
17 @dataclass(frozen=True, eq=True)
18 class SpeedscopeFrame:
19 """
20 Data class to store data needed for speedscope's concept of a
21 frame, hereafter referred to as a "speedscope frame", as opposed to
22 a "pyinstrument frame". This type must be hashable in order to use
23 it as a dictionary key; a dictionary will be used to track unique
24 speedscope frames.
25 """
26
27 name: str | None
28 file: str | None
29 line: int | None
30
31
32 class SpeedscopeEventType(Enum):
33 """Enum representing the only two types of speedscope frame events"""
34
35 OPEN = "O"
36 CLOSE = "C"
37
38
39 @dataclass
40 class SpeedscopeEvent:
41 """
42 Data class to store speedscope's concept of an "event", which
43 corresponds to opening or closing stack frames as functions or
44 methods are entered or exited.
45 """
46
47 type: SpeedscopeEventType
48 at: float
49 frame: int
50
51
52 @dataclass
53 class SpeedscopeProfile:
54 """
55 Data class to store speedscope's concept of a "profile".
56 """
57
58 name: str
59 events: list[SpeedscopeEvent]
60 end_value: float
61 start_value: float = 0.0
62 type: str = "evented"
63 unit: str = "seconds"
64
65
66 @dataclass
67 class SpeedscopeFile:
68 """
69 Data class encoding fields in speedscope's JSON file schema
70 """
71
72 name: str
73 profiles: list[SpeedscopeProfile]
74 shared: dict[str, list[SpeedscopeFrame]]
75 schema: str = "https://www.speedscope.app/file-format-schema.json"
76 active_profile_index: None = None
77 exporter: str = "pyinstrument"
78
79
80 SpeedscopeFrameDictType = Dict[str, Union[str, int, None]]
81 SpeedscopeEventDictType = Dict[str, Union[SpeedscopeEventType, float, int]]
82
83
84 class SpeedscopeEncoder(json.JSONEncoder):
85 """
86 Encoder class used by json.dumps to serialize the various
87 speedscope data classes.
88 """
89
90 def default(self, o: Any) -> Any:
91 if isinstance(o, SpeedscopeFile):
92 return {
93 "$schema": o.schema,
94 "name": o.name,
95 "activeProfileIndex": o.active_profile_index,
96 "exporter": o.exporter,
97 "profiles": o.profiles,
98 "shared": o.shared,
99 }
100 if isinstance(o, SpeedscopeProfile):
101 return {
102 "type": o.type,
103 "name": o.name,
104 "unit": o.unit,
105 "startValue": o.start_value,
106 "endValue": o.end_value,
107 "events": o.events,
108 }
109 if isinstance(o, (SpeedscopeFrame, SpeedscopeEvent)):
110 d: SpeedscopeFrameDictType | SpeedscopeEventDictType = o.__dict__
111 return d
112 if isinstance(o, SpeedscopeEventType):
113 return o.value
114 return json.JSONEncoder.default(self, o)
115
116
117 class SpeedscopeRenderer(FrameRenderer):
118 """
119 Outputs a tree of JSON conforming to the speedscope schema documented at
120
121 wiki: https://github.com/jlfwong/speedscope/wiki/Importing-from-custom-sources
122 schema: https://www.speedscope.app/file-format-schema.json
123 spec: https://github.com/jlfwong/speedscope/blob/main/src/lib/file-format-spec.ts
124 example: https://github.com/jlfwong/speedscope/blob/main/sample/profiles/speedscope/0.0.1/simple.speedscope.json
125
126 """
127
128 output_file_extension = "speedscope.json"
129
130 def __init__(self, **kwargs: Any):
131 super().__init__(**kwargs)
132
133 # Member holding a running total of wall clock time needed to
134 # compute the times at which events occur
135 self._event_time: float = 0.0
136
137 # Map of speedscope frames to speedscope frame indices, needed
138 # to construct evented speedscope profiles; exploits LIFO
139 # property of popinfo method in Python 3.7+ dictionaries. This
140 # dictionary is used to build up the "shared" JSON array in
141 # speedscope's schema.
142 self._frame_to_index: dict[SpeedscopeFrame, int] = {}
143
144 def render_frame(self, frame: Frame | None) -> list[SpeedscopeEvent]:
145 """
146 Builds up a list of speedscope events that are used to populate the
147 "events" array in speedscope-formatted JSON.
148
149 This method has two notable side effects:
150
151 * it populates the self._frame_to_index dictionary that matches
152 speedscope frames with their positions in the "shared" array of
153 speedscope output; this dictionary will be used to write this
154 "shared" array in the render method
155
156 * it accumulates a running total of time elapsed by
157 accumulating the self_time spent in each pyinstrument frame;
158 this running total is used by speedscope events to construct
159 a flame chart.
160 """
161
162 # if frame is None, recursion bottoms out; no event frames
163 # need to be added
164 if frame is None:
165 return []
166
167 # Otherwise, form a speedscope frame and add it to the frame
168 # to index map if the frame is not already a key in that map.
169 sframe = SpeedscopeFrame(frame.function, frame.file_path, frame.line_no)
170 if sframe not in self._frame_to_index:
171 self._frame_to_index[sframe] = len(self._frame_to_index)
172
173 # Get the frame index and add a speedscope event corresponding
174 # to opening a stack frame.
175 sframe_index = self._frame_to_index[sframe]
176 open_event = SpeedscopeEvent(SpeedscopeEventType.OPEN, self._event_time, sframe_index)
177 events_array: list[SpeedscopeEvent] = [open_event]
178
179 # Add stack frame open and close events for all child frames
180 # of this frame.
181 for child in frame.children:
182 events_array.extend(self.render_frame(child))
183
184 # Update event time for closing this stack frame.
185 #
186 # If number of frames approaches 1e16 * desired accuracy
187 # level, consider using Neumaier-Kahan summation; improves
188 # worst-case relative accuracy of sum from O(num_summands *
189 # eps) to (2 * eps + O(num_summands * eps * eps)), where eps
190 # is IEEE-754 double precision unit roundoff, approximately
191 # 1e-16. Average case relative accuracy expressions replace
192 # num_summands with sqrt(num_summands). However, Kahan
193 # summation quadruples operation count of sum, and Neumaier
194 # variant also adds a branch & swap for each summand. Pairwise
195 # summation isn't an option here because a running total is
196 # needed.
197
198 self._event_time += frame.absorbed_time
199 if frame.is_synthetic_leaf:
200 # only time contained within leaf nodes is real time i.e. not the sum of children
201 self._event_time += frame.time
202
203 # Add event closing this stack frame.
204 close_event = SpeedscopeEvent(SpeedscopeEventType.CLOSE, self._event_time, sframe_index)
205 events_array.append(close_event)
206
207 return events_array
208
209 def render(self, session: Session):
210 frame = self.preprocess(session.root_frame())
211
212 id_: str = time.strftime("%Y-%m-%dT%H-%M-%S", time.localtime(session.start_time))
213 name: str = f"CPU profile for '{session.target_description}' at {id_}"
214
215 sprofile_list: list[SpeedscopeProfile] = [
216 SpeedscopeProfile(name, self.render_frame(frame), session.duration)
217 ]
218
219 # Exploits Python 3.7+ dictionary property of iterating over
220 # keys in insertion order to build the list of speedscope
221 # frames.
222 sframe_list: list[SpeedscopeFrame] = [sframe for sframe in iter(self._frame_to_index)]
223
224 shared_dict = {"frames": sframe_list}
225 speedscope_file = SpeedscopeFile(name, sprofile_list, shared_dict)
226
227 return "%s\n" % json.dumps(speedscope_file, cls=SpeedscopeEncoder)
228
229 def default_processors(self) -> ProcessorList:
230 """
231 Default Processors for speedscope renderer; note that
232 processors.aggregate_repeated_calls is removed because
233 speedscope is a timeline-based format.
234 """
235 return [
236 processors.remove_importlib,
237 processors.remove_tracebackhide,
238 processors.merge_consecutive_self_time,
239 processors.remove_irrelevant_nodes,
240 processors.remove_unnecessary_self_time_nodes,
241 processors.remove_first_pyinstrument_frames_processor,
242 ]