Debian Codegraph @

pyinstrument/renderers/console.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import math
4 import re
5 import textwrap
6 import time
7 from typing import Any, Dict, List, Tuple
8
9 import pyinstrument
10 from pyinstrument import processors
11 from pyinstrument.frame import Frame, FrameGroup
12 from pyinstrument.renderers.base import FrameRenderer, ProcessorList, Renderer
13 from pyinstrument.session import Session
14 from pyinstrument.typing import LiteralStr
15 from pyinstrument.util import truncate
16
17 # pyright: strict
18
19 FlatTimeMode = LiteralStr["self", "total"]
20
21
22 class ConsoleRenderer(FrameRenderer):
23 """
24 Produces text-based output, suitable for text files or ANSI-compatible
25 consoles.
26 """
27
28 def __init__(
29 self,
30 show_all: bool = False,
31 timeline: bool = False,
32 processor_options: dict[str, Any] | None = None,
33 unicode: bool = False,
34 color: bool = False,
35 flat: bool = False,
36 time: LiteralStr["seconds", "percent_of_total"] = "seconds",
37 flat_time: FlatTimeMode = "self",
38 short_mode: bool = False,
39 ) -> None:
40 """
41 :param unicode: Use unicode, like box-drawing characters in the output.
42 :param color: Enable color support, using ANSI color sequences.
43 :param flat: Display a flat profile instead of a call graph.
44 :param time: How to display the duration of each frame - ``'seconds'`` or ``'percent_of_total'``
45 :param flat_time: Show ``'self'`` time or ``'total'`` time (including children) in flat profile.
46 :param short_mode: Display a short version of the output.
47 :param show_all: See :class:`FrameRenderer`.
48 :param timeline: See :class:`FrameRenderer`.
49 :param processor_options: See :class:`FrameRenderer`.
50 """
51 super().__init__(show_all=show_all, timeline=timeline, processor_options=processor_options)
52 self.unicode = unicode
53 self.color = color
54 self.flat = flat
55 self.time = time
56 self.flat_time = flat_time
57 self.short_mode = short_mode
58
59 if self.flat and self.timeline:
60 raise Renderer.MisconfigurationError("Cannot use timeline and flat options together.")
61
62 self.colors = self.colors_enabled if color else self.colors_disabled
63
64 def render(self, session: Session) -> str:
65 result = self.render_preamble(session)
66
67 frame = self.preprocess(session.root_frame())
68 indent = ". " if self.short_mode else ""
69 precision = math.ceil(-math.log10(min(max(1e-9, session.max_interval), 1)))
70
71 if frame is None:
72 result += f"{indent}No samples were recorded.\n"
73 else:
74 self.root_frame = frame
75
76 if self.flat:
77 result += self.render_frame_flat(self.root_frame, precision=precision)
78 else:
79 result += self.render_frame(
80 self.root_frame, precision=precision, indent=indent, child_indent=indent
81 )
82
83 result += f"{indent}\n"
84
85 if self.short_mode:
86 result += "." * 53 + "\n\n"
87
88 return result
89
90 # pylint: disable=W1401
91 def render_preamble(self, session: Session) -> str:
92 if self.short_mode:
93 return textwrap.dedent(
94 f"""
95 pyinstrument ........................................
96 .
97 . {session.target_description}
98 .
99 """
100 )
101
102 lines = [
103 r"",
104 r" _ ._ __/__ _ _ _ _ _/_ ",
105 r" /_//_/// /_\ / //_// / //_'/ // ",
106 r"/ _/ {:>20}".format("v" + pyinstrument.__version__),
107 ]
108
109 lines[1] += " Recorded: {:<9}".format(
110 time.strftime("%X", time.localtime(session.start_time))
111 )
112 lines[2] += f" Duration: {session.duration:<9.3f}"
113 lines[1] += f" Samples: {session.sample_count}"
114 lines[2] += f" CPU time: {session.cpu_time:.3f}"
115
116 lines.append("")
117 lines.append(session.target_description)
118 lines.append("")
119 lines.append("")
120
121 return "\n".join(lines)
122
123 def should_render_frame(self, frame: Frame) -> bool:
124 if frame.group and not self.should_ignore_group(frame.group):
125 return self.should_render_frame_in_group(frame)
126 return True
127
128 def should_render_frame_in_group(self, frame: Frame) -> bool:
129 # Only render the root frame, or frames that are significant
130 assert frame.group
131 return (
132 frame.group.root == frame
133 or frame.total_self_time > 0.2 * self.root_frame.time
134 or frame in frame.group.exit_frames
135 )
136
137 def should_ignore_group(self, group: FrameGroup) -> bool:
138 """
139 If a group is ignored, its frames are all printed - they're not hidden.
140 """
141 hidden_frames = [f for f in group.frames if not self.should_render_frame_in_group(f)]
142 # don't bother printing groups with one/zero hidden frames
143 return len(hidden_frames) < 2
144
145 def group_description(self, group: FrameGroup) -> str:
146 hidden_frames = [f for f in group.frames if not self.should_render_frame(f)]
147 libraries = self.libraries_for_frames(hidden_frames)
148 return "[{count} frames hidden] {c.faint}{libraries}{c.end}\n".format(
149 count=len(hidden_frames),
150 libraries=truncate(", ".join(libraries), 40),
151 c=self.colors,
152 )
153
154 def libraries_for_frames(self, frames: list[Frame]) -> list[str]:
155 libraries: list[str] = []
156 for frame in frames:
157 if frame.file_path_short:
158 library = re.split(r"[\\/\.]", frame.file_path_short, maxsplit=1)[0]
159
160 if library and library not in libraries:
161 libraries.append(library)
162 return libraries
163
164 def render_frame(
165 self, frame: Frame, precision: int, indent: str = "", child_indent: str = ""
166 ) -> str:
167 if self.should_render_frame(frame):
168 result = f"{indent}{self.frame_description(frame, precision=precision)}\n"
169
170 if self.unicode:
171 indents = {"├": "├─ ", "│": "│ ", "└": "└─ ", " ": " "}
172 else:
173 indents = {"├": "|- ", "│": "| ", "└": "`- ", " ": " "}
174
175 if (
176 frame.group
177 and frame.group.root == frame
178 and not self.should_ignore_group(frame.group)
179 ):
180 result += f"{child_indent} {self.group_description(frame.group)}"
181 for key in indents:
182 indents[key] = " "
183 else:
184 result = ""
185 indents = {"├": "", "│": "", "└": "", " ": ""}
186
187 if frame.children:
188 children_to_be_rendered_indices = [
189 i for i, f in enumerate(frame.children) if self.should_render_frame(f)
190 ]
191 last_rendered_child_index = (
192 children_to_be_rendered_indices[-1] if children_to_be_rendered_indices else -1
193 )
194
195 for i, child in enumerate(frame.children):
196 if i < last_rendered_child_index:
197 c_indent = child_indent + indents["├"]
198 cc_indent = child_indent + indents["│"]
199 else:
200 c_indent = child_indent + indents["└"]
201 cc_indent = child_indent + indents[" "]
202 result += self.render_frame(
203 child, precision=precision, indent=c_indent, child_indent=cc_indent
204 )
205
206 return result
207
208 def render_frame_flat(self, frame: Frame, precision: int) -> str:
209 def walk(frame: Frame):
210 frame_id_to_time[frame.identifier] = (
211 frame_id_to_time.get(frame.identifier, 0) + frame.total_self_time
212 if self.flat_time == "self"
213 else frame.time
214 )
215
216 frame_id_to_frame[frame.identifier] = frame
217
218 for child in frame.children:
219 walk(child)
220
221 frame_id_to_time: Dict[str, float] = {}
222 frame_id_to_frame: Dict[str, Frame] = {}
223
224 walk(frame)
225
226 id_time_pairs: List[Tuple[str, float]] = sorted(
227 frame_id_to_time.items(), key=(lambda item: item[1]), reverse=True
228 )
229
230 if not self.show_all:
231 # remove nodes that represent less than 0.1% of the total time
232 id_time_pairs = [
233 pair for pair in id_time_pairs if pair[1] / self.root_frame.time > 0.001
234 ]
235
236 result = ""
237
238 for frame_id, self_time in id_time_pairs:
239 result += self.frame_description(
240 frame_id_to_frame[frame_id], precision=precision, override_time=self_time
241 )
242 result += "\n"
243
244 return result
245
246 def frame_description(
247 self, frame: Frame, *, precision: int = 3, override_time: float | None = None
248 ) -> str:
249 time = override_time if override_time is not None else frame.time
250 time_color = self._ansi_color_for_time(time)
251
252 if self.time == "percent_of_total":
253 time_str = f"{self.frame_proportion_of_total_time(time) * 100:.1f}%"
254 else:
255 time_str = f"{time:.{precision}f}"
256
257 value_str = f"{time_color}{time_str}{self.colors.end}"
258
259 class_name = frame.class_name
260 if class_name:
261 function_name = f"{class_name}.{frame.function}"
262 else:
263 function_name = frame.function
264 function_color = self._ansi_color_for_name(frame)
265 function_str = f"{function_color}{function_name}{self.colors.end}"
266
267 code_position_short = frame.code_position_short()
268 if code_position_short:
269 code_position_str = f"{self.colors.faint}{code_position_short}{self.colors.end}"
270 else:
271 code_position_str = ""
272
273 return f"{value_str} {function_str} {code_position_str}"
274
275 def frame_proportion_of_total_time(self, time: float) -> float:
276 if self.root_frame.time == 0:
277 return 1
278 return time / self.root_frame.time
279
280 def _ansi_color_for_time(self, time: float) -> str:
281 proportion_of_total = self.frame_proportion_of_total_time(time)
282
283 if proportion_of_total > 0.6:
284 return self.colors.red
285 elif proportion_of_total > 0.2:
286 return self.colors.yellow
287 elif proportion_of_total > 0.05:
288 return self.colors.green
289 else:
290 return self.colors.bright_green + self.colors.faint
291
292 def _ansi_color_for_name(self, frame: Frame) -> str:
293 if frame.is_application_code:
294 return self.colors.bg_dark_blue_255 + self.colors.white_255
295 else:
296 return ""
297
298 def default_processors(self) -> ProcessorList:
299 return [
300 processors.remove_importlib,
301 processors.remove_tracebackhide,
302 processors.merge_consecutive_self_time,
303 processors.aggregate_repeated_calls,
304 processors.remove_irrelevant_nodes,
305 processors.remove_unnecessary_self_time_nodes,
306 processors.remove_first_pyinstrument_frames_processor,
307 processors.group_library_frames_processor,
308 ]
309
310 class colors_enabled:
311 red = "\033[31m"
312 green = "\033[32m"
313 yellow = "\033[33m"
314 blue = "\033[34m"
315 cyan = "\033[36m"
316 bright_green = "\033[92m"
317 white = "\033[37m\033[97m"
318
319 bg_dark_blue_255 = "\033[48;5;24m"
320 white_255 = "\033[38;5;15m"
321
322 bold = "\033[1m"
323 faint = "\033[2m"
324
325 end = "\033[0m"
326
327 class colors_disabled:
328 red = ""
329 green = ""
330 yellow = ""
331 blue = ""
332 cyan = ""
333 bright_green = ""
334 white = ""
335
336 bg_dark_blue_255 = ""
337 white_255 = ""
338
339 bold = ""
340 faint = ""
341
342 end = ""