| 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 |
|
| 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 |
|
| 134 |
|
| 135 |
self._event_time: float = 0.0 |
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 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 |
|
| 163 |
|
| 164 |
if frame is None: |
| 165 |
return [] |
| 166 |
|
| 167 |
|
| 168 |
|
| 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 |
|
| 174 |
|
| 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 |
|
| 180 |
|
| 181 |
for child in frame.children: |
| 182 |
events_array.extend(self.render_frame(child)) |
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
self._event_time += frame.absorbed_time |
| 199 |
if frame.is_synthetic_leaf: |
| 200 |
|
| 201 |
self._event_time += frame.time |
| 202 |
|
| 203 |
|
| 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 |
|
| 220 |
|
| 221 |
|
| 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 |
] |