| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
import os |
| 5 |
import sys |
| 6 |
from collections import deque |
| 7 |
from typing import Any, Sequence |
| 8 |
|
| 9 |
from pyinstrument.frame import Frame |
| 10 |
from pyinstrument.frame_info import frame_info_get_identifier |
| 11 |
from pyinstrument.frame_ops import FrameRecordType, build_frame_tree |
| 12 |
from pyinstrument.typing import PathOrStr |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
ASSERTION_MESSAGE = ( |
| 18 |
"Please raise an issue at https://github.com/joerick/pyinstrument/issues and " |
| 19 |
"let me know how you caused this error!" |
| 20 |
) |
| 21 |
|
| 22 |
|
| 23 |
class Session: |
| 24 |
def __init__( |
| 25 |
self, |
| 26 |
frame_records: list[FrameRecordType], |
| 27 |
start_time: float, |
| 28 |
duration: float, |
| 29 |
min_interval: float, |
| 30 |
max_interval: float, |
| 31 |
sample_count: int, |
| 32 |
start_call_stack: list[str], |
| 33 |
target_description: str, |
| 34 |
cpu_time: float, |
| 35 |
sys_path: list[str], |
| 36 |
sys_prefixes: list[str], |
| 37 |
): |
| 38 |
"""Session() |
| 39 |
|
| 40 |
Represents a profile session, contains the data collected during a profile session. |
| 41 |
|
| 42 |
:meta private: |
| 43 |
""" |
| 44 |
self.frame_records = frame_records |
| 45 |
self.start_time = start_time |
| 46 |
self.duration = duration |
| 47 |
self.min_interval = min_interval |
| 48 |
self.max_interval = max_interval |
| 49 |
self.sample_count = sample_count |
| 50 |
self.start_call_stack = start_call_stack |
| 51 |
self.target_description = target_description |
| 52 |
self.cpu_time = cpu_time |
| 53 |
self.sys_path = sys_path |
| 54 |
self.sys_prefixes = sys_prefixes |
| 55 |
self._short_file_path_cache = {} |
| 56 |
|
| 57 |
@staticmethod |
| 58 |
def load(filename: PathOrStr) -> Session: |
| 59 |
""" |
| 60 |
Load a previously saved session from disk. |
| 61 |
|
| 62 |
:param filename: The path to load from. |
| 63 |
:rtype: Session |
| 64 |
""" |
| 65 |
with open(filename) as f: |
| 66 |
return Session.from_json(json.load(f)) |
| 67 |
|
| 68 |
def save(self, filename: PathOrStr) -> None: |
| 69 |
""" |
| 70 |
Saves a Session object to disk, in a JSON format. |
| 71 |
|
| 72 |
:param filename: The path to save to. Using the ``.pyisession`` extension is recommended. |
| 73 |
""" |
| 74 |
with open(filename, "w") as f: |
| 75 |
json.dump(self.to_json(), f) |
| 76 |
|
| 77 |
def to_json(self, include_frame_records: bool = True): |
| 78 |
result: dict[str, Any] = { |
| 79 |
"start_time": self.start_time, |
| 80 |
"duration": self.duration, |
| 81 |
"min_interval": self.min_interval, |
| 82 |
"max_interval": self.max_interval, |
| 83 |
"sample_count": self.sample_count, |
| 84 |
"start_call_stack": self.start_call_stack, |
| 85 |
"target_description": self.target_description, |
| 86 |
"cpu_time": self.cpu_time, |
| 87 |
"sys_path": self.sys_path, |
| 88 |
"sys_prefixes": self.sys_prefixes, |
| 89 |
} |
| 90 |
|
| 91 |
if include_frame_records: |
| 92 |
result["frame_records"] = self.frame_records |
| 93 |
|
| 94 |
return result |
| 95 |
|
| 96 |
@staticmethod |
| 97 |
def from_json(json_dict: dict[str, Any]): |
| 98 |
return Session( |
| 99 |
frame_records=json_dict["frame_records"], |
| 100 |
start_time=json_dict["start_time"], |
| 101 |
min_interval=json_dict.get("min_interval", 0.001), |
| 102 |
max_interval=json_dict.get("max_interval", 0.001), |
| 103 |
duration=json_dict["duration"], |
| 104 |
sample_count=json_dict["sample_count"], |
| 105 |
start_call_stack=json_dict["start_call_stack"], |
| 106 |
target_description=json_dict["target_description"], |
| 107 |
cpu_time=json_dict["cpu_time"] or 0, |
| 108 |
sys_path=json_dict.get("sys_path", sys.path), |
| 109 |
sys_prefixes=json_dict.get("sys_prefixes", Session.current_sys_prefixes()), |
| 110 |
) |
| 111 |
|
| 112 |
@staticmethod |
| 113 |
def combine(session1: Session, session2: Session) -> Session: |
| 114 |
""" |
| 115 |
Combines two :class:`Session` objects. |
| 116 |
|
| 117 |
Sessions that are joined in this way probably shouldn't be interpreted |
| 118 |
as timelines, because the samples are simply concatenated. But |
| 119 |
aggregate views (the default) of this data will work. |
| 120 |
|
| 121 |
:rtype: Session |
| 122 |
""" |
| 123 |
if session1.start_time > session2.start_time: |
| 124 |
|
| 125 |
session1, session2 = session2, session1 |
| 126 |
|
| 127 |
return Session( |
| 128 |
frame_records=session1.frame_records + session2.frame_records, |
| 129 |
start_time=session1.start_time, |
| 130 |
min_interval=min(session1.min_interval, session2.min_interval), |
| 131 |
max_interval=max(session1.max_interval, session2.max_interval), |
| 132 |
duration=session1.duration + session2.duration, |
| 133 |
sample_count=session1.sample_count + session2.sample_count, |
| 134 |
start_call_stack=session1.start_call_stack, |
| 135 |
target_description=session1.target_description, |
| 136 |
cpu_time=session1.cpu_time + session2.cpu_time, |
| 137 |
sys_path=( |
| 138 |
session1.sys_path + [p for p in session2.sys_path if p not in session1.sys_path] |
| 139 |
), |
| 140 |
sys_prefixes=list(set([*session1.sys_prefixes, *session2.sys_prefixes])), |
| 141 |
) |
| 142 |
|
| 143 |
@staticmethod |
| 144 |
def current_sys_prefixes() -> list[str]: |
| 145 |
return [sys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix] |
| 146 |
|
| 147 |
def root_frame(self, trim_stem: bool = True) -> Frame | None: |
| 148 |
""" |
| 149 |
Parses the internal frame records and returns a tree of :class:`Frame` |
| 150 |
objects. This object can be rendered using a :class:`Renderer` |
| 151 |
object. |
| 152 |
|
| 153 |
:rtype: A :class:`Frame` object, or None if the session is empty. |
| 154 |
""" |
| 155 |
root_frame = build_frame_tree(self.frame_records, context=self) |
| 156 |
|
| 157 |
if root_frame is None: |
| 158 |
return None |
| 159 |
|
| 160 |
if trim_stem: |
| 161 |
root_frame = self._trim_stem(root_frame) |
| 162 |
|
| 163 |
return root_frame |
| 164 |
|
| 165 |
def _trim_stem(self, frame: Frame): |
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
start_stack = deque(frame_info_get_identifier(info) for info in self.start_call_stack) |
| 170 |
|
| 171 |
if start_stack.popleft() != frame.identifier: |
| 172 |
|
| 173 |
return frame |
| 174 |
|
| 175 |
while frame.total_self_time == 0 and len(frame.children) == 1: |
| 176 |
|
| 177 |
if len(start_stack) == 0 or frame.children[0].identifier != start_stack.popleft(): |
| 178 |
break |
| 179 |
|
| 180 |
frame = frame.children[0] |
| 181 |
|
| 182 |
frame.remove_from_parent() |
| 183 |
return frame |
| 184 |
|
| 185 |
_short_file_path_cache: dict[str, str] |
| 186 |
|
| 187 |
def shorten_path(self, path: str) -> str: |
| 188 |
""" |
| 189 |
Shorten a path to a more readable form, relative to sys_path. Used by |
| 190 |
Frame.short_file_path. |
| 191 |
""" |
| 192 |
if path in self._short_file_path_cache: |
| 193 |
return self._short_file_path_cache[path] |
| 194 |
|
| 195 |
result = path |
| 196 |
|
| 197 |
|
| 198 |
if len(path.split(os.sep)) > 1: |
| 199 |
for sys_path_entry in self.sys_path: |
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
try: |
| 206 |
candidate = os.path.relpath(path, sys_path_entry) |
| 207 |
except ValueError: |
| 208 |
continue |
| 209 |
|
| 210 |
if not result or (len(candidate.split(os.sep)) < len(result.split(os.sep))): |
| 211 |
result = candidate |
| 212 |
|
| 213 |
self._short_file_path_cache[path] = result |
| 214 |
|
| 215 |
return result |
| 216 |
|
| 217 |
@staticmethod |
| 218 |
def _resample_frame_records( |
| 219 |
frame_records: Sequence[FrameRecordType], interval: float |
| 220 |
) -> list[FrameRecordType]: |
| 221 |
""" |
| 222 |
Resample frame records to a given interval. Discards samples as needed. |
| 223 |
""" |
| 224 |
result: list[FrameRecordType] = [] |
| 225 |
accumulated_time = 0.0 |
| 226 |
|
| 227 |
for frame_info_stack, time in frame_records: |
| 228 |
accumulated_time += time |
| 229 |
|
| 230 |
if accumulated_time >= interval: |
| 231 |
result.append((frame_info_stack, accumulated_time)) |
| 232 |
accumulated_time = accumulated_time % interval |
| 233 |
|
| 234 |
return result |
| 235 |
|
| 236 |
def resample(self, interval: float) -> Session: |
| 237 |
""" |
| 238 |
Returns a new Session object with frame records resampled to the given interval. |
| 239 |
|
| 240 |
:param interval: The desired sampling interval in seconds. |
| 241 |
:rtype: Session |
| 242 |
""" |
| 243 |
new_frame_records = self._resample_frame_records(self.frame_records, interval) |
| 244 |
|
| 245 |
return Session( |
| 246 |
frame_records=new_frame_records, |
| 247 |
start_time=self.start_time, |
| 248 |
duration=self.duration, |
| 249 |
min_interval=interval, |
| 250 |
max_interval=interval, |
| 251 |
sample_count=len(new_frame_records), |
| 252 |
start_call_stack=self.start_call_stack, |
| 253 |
target_description=self.target_description, |
| 254 |
cpu_time=self.cpu_time, |
| 255 |
sys_path=self.sys_path, |
| 256 |
sys_prefixes=self.sys_prefixes, |
| 257 |
) |