| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import inspect |
| 4 |
import os |
| 5 |
import sys |
| 6 |
import time |
| 7 |
import types |
| 8 |
from pathlib import Path |
| 9 |
from time import process_time |
| 10 |
from typing import IO, Any |
| 11 |
|
| 12 |
from pyinstrument import renderers |
| 13 |
from pyinstrument.frame import AWAIT_FRAME_IDENTIFIER, OUT_OF_CONTEXT_FRAME_IDENTIFIER |
| 14 |
from pyinstrument.renderers.console import FlatTimeMode |
| 15 |
from pyinstrument.session import Session |
| 16 |
from pyinstrument.stack_sampler import AsyncState, StackSampler, build_call_stack, get_stack_sampler |
| 17 |
from pyinstrument.typing import LiteralStr, TypeAlias |
| 18 |
from pyinstrument.util import file_supports_color, file_supports_unicode |
| 19 |
|
| 20 |
# pyright: strict |
| 21 |
|
| 22 |
|
| 23 |
class ActiveProfilerSession: |
| 24 |
frame_records: list[tuple[list[str], float]] |
| 25 |
|
| 26 |
def __init__( |
| 27 |
self, |
| 28 |
start_time: float, |
| 29 |
start_process_time: float, |
| 30 |
start_call_stack: list[str], |
| 31 |
target_description: str, |
| 32 |
interval: float, |
| 33 |
) -> None: |
| 34 |
self.start_time = start_time |
| 35 |
self.start_process_time = start_process_time |
| 36 |
self.start_call_stack = start_call_stack |
| 37 |
self.frame_records = [] |
| 38 |
self.target_description = target_description |
| 39 |
self.interval = interval |
| 40 |
|
| 41 |
|
| 42 |
AsyncMode: TypeAlias = LiteralStr["enabled", "disabled", "strict"] |
| 43 |
|
| 44 |
|
| 45 |
class Profiler: |
| 46 |
""" |
| 47 |
The profiler - this is the main way to use pyinstrument. |
| 48 |
""" |
| 49 |
|
| 50 |
_last_session: Session | None |
| 51 |
_active_session: ActiveProfilerSession | None |
| 52 |
_interval: float |
| 53 |
_async_mode: AsyncMode |
| 54 |
use_timing_thread: bool | None |
| 55 |
|
| 56 |
def __init__( |
| 57 |
self, |
| 58 |
interval: float = 0.001, |
| 59 |
async_mode: AsyncMode = "enabled", |
| 60 |
use_timing_thread: bool | None = None, |
| 61 |
): |
| 62 |
""" |
| 63 |
Note the profiling will not start until :func:`start` is called. |
| 64 |
|
| 65 |
:param interval: See :attr:`interval`. |
| 66 |
:param async_mode: See :attr:`async_mode`. |
| 67 |
:param use_timing_thread: If True, the profiler will use a separate |
| 68 |
thread to keep track of time. This is useful if you're on a system |
| 69 |
where getting the time has significant overhead. |
| 70 |
""" |
| 71 |
self._interval = interval |
| 72 |
self._last_session = None |
| 73 |
self._active_session = None |
| 74 |
self._async_mode = async_mode |
| 75 |
self.use_timing_thread = use_timing_thread |
| 76 |
|
| 77 |
@property |
| 78 |
def interval(self) -> float: |
| 79 |
""" |
| 80 |
The minimum time, in seconds, between each stack sample. This translates into the |
| 81 |
resolution of the sampling. |
| 82 |
""" |
| 83 |
return self._interval |
| 84 |
|
| 85 |
@property |
| 86 |
def async_mode(self) -> AsyncMode: |
| 87 |
""" |
| 88 |
Configures how this Profiler tracks time in a program that uses |
| 89 |
async/await. |
| 90 |
|
| 91 |
``enabled`` |
| 92 |
When this profiler sees an ``await``, time is logged in the function |
| 93 |
that awaited, rather than observing other coroutines or the event |
| 94 |
loop. |
| 95 |
|
| 96 |
``disabled`` |
| 97 |
This profiler doesn't attempt to track ``await``. In a program that |
| 98 |
uses async/await, this will interleave other coroutines and event |
| 99 |
loop machinery in the profile. Use this option if async support is |
| 100 |
causing issues in your use case, or if you want to run multiple |
| 101 |
profilers at once. |
| 102 |
|
| 103 |
``strict`` |
| 104 |
Instructs the profiler to only profile the current |
| 105 |
`async context <https://docs.python.org/3/library/contextvars.html>`_. |
| 106 |
Frames that are observed in an other context are ignored, tracked |
| 107 |
instead as ``<out-of-context>``. |
| 108 |
""" |
| 109 |
return self._async_mode |
| 110 |
|
| 111 |
@property |
| 112 |
def last_session(self) -> Session | None: |
| 113 |
""" |
| 114 |
The previous session recorded by the Profiler. |
| 115 |
""" |
| 116 |
return self._last_session |
| 117 |
|
| 118 |
def start( |
| 119 |
self, caller_frame: types.FrameType | None = None, target_description: str | None = None |
| 120 |
): |
| 121 |
""" |
| 122 |
Instructs the profiler to start - to begin observing the program's execution and recording |
| 123 |
frames. |
| 124 |
|
| 125 |
The normal way to invoke ``start()`` is with a new instance, but you can restart a Profiler |
| 126 |
that was previously running, too. The sessions are combined. |
| 127 |
|
| 128 |
:param caller_frame: Set this to override the default behaviour of treating the caller of |
| 129 |
``start()`` as the 'start_call_stack' - the instigator of the profile. Most |
| 130 |
renderers will trim the 'root' from the call stack up to this frame, to |
| 131 |
present a simpler output. |
| 132 |
|
| 133 |
You might want to set this to ``inspect.currentframe().f_back`` if you are |
| 134 |
writing a library that wraps pyinstrument. |
| 135 |
""" |
| 136 |
|
| 137 |
if caller_frame is None: |
| 138 |
caller_frame = inspect.currentframe().f_back # type: ignore |
| 139 |
|
| 140 |
if target_description is None: |
| 141 |
if caller_frame is None: |
| 142 |
target_description = "Profile at unknown location" |
| 143 |
else: |
| 144 |
target_description = "Profile at {}:{}".format( |
| 145 |
caller_frame.f_code.co_filename, caller_frame.f_lineno |
| 146 |
) |
| 147 |
|
| 148 |
if self.is_running: |
| 149 |
raise ValueError("Profiler is already running.") |
| 150 |
|
| 151 |
try: |
| 152 |
self._active_session = ActiveProfilerSession( |
| 153 |
start_time=time.time(), |
| 154 |
start_process_time=process_time(), |
| 155 |
start_call_stack=build_call_stack(caller_frame, "initial", None), |
| 156 |
target_description=target_description, |
| 157 |
interval=self.interval, |
| 158 |
) |
| 159 |
|
| 160 |
use_async_context = self.async_mode != "disabled" |
| 161 |
get_stack_sampler().subscribe( |
| 162 |
self._sampler_saw_call_stack, |
| 163 |
desired_interval=self.interval, |
| 164 |
use_async_context=use_async_context, |
| 165 |
use_timing_thread=self.use_timing_thread, |
| 166 |
) |
| 167 |
except: |
| 168 |
self._active_session = None |
| 169 |
raise |
| 170 |
|
| 171 |
def stop(self) -> Session: |
| 172 |
""" |
| 173 |
Stops the profiler observing, and sets :attr:`last_session` |
| 174 |
to the captured session. |
| 175 |
|
| 176 |
:return: The captured session. |
| 177 |
""" |
| 178 |
if not self._active_session: |
| 179 |
raise RuntimeError("This profiler is not currently running.") |
| 180 |
|
| 181 |
try: |
| 182 |
get_stack_sampler().unsubscribe(self._sampler_saw_call_stack) |
| 183 |
except StackSampler.SubscriberNotFound: |
| 184 |
raise RuntimeError( |
| 185 |
"Failed to stop profiling. Make sure that you start/stop profiling on the same thread." |
| 186 |
) |
| 187 |
|
| 188 |
cpu_time = process_time() - self._active_session.start_process_time |
| 189 |
|
| 190 |
active_session = self._active_session |
| 191 |
self._active_session = None |
| 192 |
|
| 193 |
session = Session( |
| 194 |
frame_records=active_session.frame_records, |
| 195 |
start_time=active_session.start_time, |
| 196 |
duration=time.time() - active_session.start_time, |
| 197 |
min_interval=active_session.interval, |
| 198 |
max_interval=active_session.interval, |
| 199 |
sample_count=len(active_session.frame_records), |
| 200 |
target_description=active_session.target_description, |
| 201 |
start_call_stack=active_session.start_call_stack, |
| 202 |
cpu_time=cpu_time, |
| 203 |
sys_path=sys.path, |
| 204 |
sys_prefixes=Session.current_sys_prefixes(), |
| 205 |
) |
| 206 |
|
| 207 |
if self.last_session is not None: |
| 208 |
# include the previous session's data too |
| 209 |
session = Session.combine(self.last_session, session) |
| 210 |
|
| 211 |
self._last_session = session |
| 212 |
|
| 213 |
return session |
| 214 |
|
| 215 |
@property |
| 216 |
def is_running(self): |
| 217 |
""" |
| 218 |
Returns `True` if this profiler is running - i.e. observing the program execution. |
| 219 |
""" |
| 220 |
return self._active_session is not None |
| 221 |
|
| 222 |
def reset(self): |
| 223 |
""" |
| 224 |
Resets the Profiler, clearing the `last_session`. |
| 225 |
""" |
| 226 |
if self.is_running: |
| 227 |
self.stop() |
| 228 |
|
| 229 |
self._last_session = None |
| 230 |
|
| 231 |
def __enter__(self): |
| 232 |
""" |
| 233 |
Context manager support. |
| 234 |
|
| 235 |
Profilers can be used in `with` blocks! See this example: |
| 236 |
|
| 237 |
.. code-block:: python |
| 238 |
|
| 239 |
with Profiler() as p: |
| 240 |
# your code here... |
| 241 |
do_some_work() |
| 242 |
|
| 243 |
# profiling has ended. let's print the output. |
| 244 |
p.print() |
| 245 |
""" |
| 246 |
self.start(caller_frame=inspect.currentframe().f_back) # type: ignore |
| 247 |
return self |
| 248 |
|
| 249 |
def __exit__(self, *args: Any): |
| 250 |
self.stop() |
| 251 |
|
| 252 |
# pylint: disable=W0613 |
| 253 |
def _sampler_saw_call_stack( |
| 254 |
self, |
| 255 |
call_stack: list[str], |
| 256 |
time_since_last_sample: float, |
| 257 |
async_state: AsyncState | None, |
| 258 |
): |
| 259 |
if not self._active_session: |
| 260 |
raise RuntimeError( |
| 261 |
"Received a call stack without an active session. Please file an issue on pyinstrument Github describing how you made this happen!" |
| 262 |
) |
| 263 |
|
| 264 |
if ( |
| 265 |
async_state |
| 266 |
and async_state.state == "out_of_context_awaited" |
| 267 |
and self._async_mode in ["enabled", "strict"] |
| 268 |
): |
| 269 |
awaiting_coroutine_stack = async_state.info |
| 270 |
self._active_session.frame_records.append( |
| 271 |
( |
| 272 |
awaiting_coroutine_stack + [AWAIT_FRAME_IDENTIFIER], |
| 273 |
time_since_last_sample, |
| 274 |
) |
| 275 |
) |
| 276 |
elif ( |
| 277 |
async_state |
| 278 |
and async_state.state == "out_of_context_unknown" |
| 279 |
and self._async_mode == "strict" |
| 280 |
): |
| 281 |
context_exit_frame = async_state.info |
| 282 |
self._active_session.frame_records.append( |
| 283 |
( |
| 284 |
context_exit_frame + [OUT_OF_CONTEXT_FRAME_IDENTIFIER], |
| 285 |
time_since_last_sample, |
| 286 |
) |
| 287 |
) |
| 288 |
else: |
| 289 |
# regular sync code |
| 290 |
self._active_session.frame_records.append((call_stack, time_since_last_sample)) |
| 291 |
|
| 292 |
def print( |
| 293 |
self, |
| 294 |
file: IO[str] = sys.stdout, |
| 295 |
*, |
| 296 |
unicode: bool | None = None, |
| 297 |
color: bool | None = None, |
| 298 |
show_all: bool = False, |
| 299 |
timeline: bool = False, |
| 300 |
time: LiteralStr["seconds", "percent_of_total"] = "seconds", |
| 301 |
flat: bool = False, |
| 302 |
flat_time: FlatTimeMode = "self", |
| 303 |
short_mode: bool = False, |
| 304 |
processor_options: dict[str, Any] | None = None, |
| 305 |
): |
| 306 |
"""print(file=sys.stdout, *, unicode=None, color=None, show_all=False, timeline=False, time='seconds', flat=False, flat_time='self', short_mode=False, processor_options=None) |
| 307 |
|
| 308 |
Print the captured profile to the console, as rendered by :class:`renderers.ConsoleRenderer` |
| 309 |
|
| 310 |
:param file: the IO stream to write to. Could be a file descriptor or sys.stdout, sys.stderr. Defaults to sys.stdout. |
| 311 |
|
| 312 |
See :class:`renderers.ConsoleRenderer` for the other parameters. |
| 313 |
""" |
| 314 |
if unicode is None: |
| 315 |
unicode = file_supports_unicode(file) |
| 316 |
if color is None: |
| 317 |
color = file_supports_color(file) |
| 318 |
|
| 319 |
print( |
| 320 |
self.output_text( |
| 321 |
unicode=unicode, |
| 322 |
color=color, |
| 323 |
show_all=show_all, |
| 324 |
timeline=timeline, |
| 325 |
time=time, |
| 326 |
flat=flat, |
| 327 |
flat_time=flat_time, |
| 328 |
short_mode=short_mode, |
| 329 |
processor_options=processor_options, |
| 330 |
), |
| 331 |
file=file, |
| 332 |
) |
| 333 |
|
| 334 |
def output_text( |
| 335 |
self, |
| 336 |
unicode: bool = False, |
| 337 |
color: bool = False, |
| 338 |
show_all: bool = False, |
| 339 |
timeline: bool = False, |
| 340 |
time: LiteralStr["seconds", "percent_of_total"] = "seconds", |
| 341 |
flat: bool = False, |
| 342 |
flat_time: FlatTimeMode = "self", |
| 343 |
short_mode: bool = False, |
| 344 |
processor_options: dict[str, Any] | None = None, |
| 345 |
) -> str: |
| 346 |
""" |
| 347 |
Return the profile output as text, as rendered by :class:`ConsoleRenderer` |
| 348 |
|
| 349 |
See :class:`renderers.ConsoleRenderer` for parameter description. |
| 350 |
""" |
| 351 |
return self.output( |
| 352 |
renderer=renderers.ConsoleRenderer( |
| 353 |
unicode=unicode, |
| 354 |
color=color, |
| 355 |
show_all=show_all, |
| 356 |
timeline=timeline, |
| 357 |
time=time, |
| 358 |
flat=flat, |
| 359 |
flat_time=flat_time, |
| 360 |
short_mode=short_mode, |
| 361 |
processor_options=processor_options, |
| 362 |
) |
| 363 |
) |
| 364 |
|
| 365 |
def output_html( |
| 366 |
self, |
| 367 |
resample_interval: float | None = None, |
| 368 |
) -> str: |
| 369 |
""" |
| 370 |
Return the profile output as HTML, as rendered by :class:`HTMLRenderer` |
| 371 |
|
| 372 |
See :class:`renderers.HTMLRenderer` for parameter description. |
| 373 |
""" |
| 374 |
return self.output(renderer=renderers.HTMLRenderer(resample_interval=resample_interval)) |
| 375 |
|
| 376 |
def write_html( |
| 377 |
self, |
| 378 |
path: str | os.PathLike[str], |
| 379 |
timeline: bool = False, |
| 380 |
show_all: bool = False, |
| 381 |
resample_interval: float | None = None, |
| 382 |
): |
| 383 |
""" |
| 384 |
Writes the profile output as HTML to a file, as rendered by :class:`HTMLRenderer` |
| 385 |
""" |
| 386 |
file = Path(path) |
| 387 |
file.write_text( |
| 388 |
self.output( |
| 389 |
renderer=renderers.HTMLRenderer( |
| 390 |
timeline=timeline, show_all=show_all, resample_interval=resample_interval |
| 391 |
) |
| 392 |
), |
| 393 |
encoding="utf-8", |
| 394 |
) |
| 395 |
|
| 396 |
def open_in_browser(self, timeline: bool = False, resample_interval: float | None = None): |
| 397 |
""" |
| 398 |
Opens the last profile session in your web browser. |
| 399 |
""" |
| 400 |
session = self._get_last_session_or_fail() |
| 401 |
|
| 402 |
return renderers.HTMLRenderer( |
| 403 |
timeline=timeline, resample_interval=resample_interval |
| 404 |
).open_in_browser(session) |
| 405 |
|
| 406 |
def output(self, renderer: renderers.Renderer) -> str: |
| 407 |
""" |
| 408 |
Returns the last profile session, as rendered by ``renderer``. |
| 409 |
|
| 410 |
:param renderer: The renderer to use. |
| 411 |
""" |
| 412 |
session = self._get_last_session_or_fail() |
| 413 |
|
| 414 |
return renderer.render(session) |
| 415 |
|
| 416 |
def _get_last_session_or_fail(self) -> Session: |
| 417 |
if self.is_running: |
| 418 |
raise Exception("can't render profile output because this profiler is still running") |
| 419 |
|
| 420 |
if self.last_session is None: |
| 421 |
raise Exception( |
| 422 |
"can't render profile output because this profiler has not completed a profile session yet" |
| 423 |
) |
| 424 |
|
| 425 |
return self.last_session |