Debian Codegraph @

pyinstrument/context_manager.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import functools
4 import inspect
5 import sys
6 import typing
7
8 from pyinstrument.profiler import AsyncMode, Profiler
9 from pyinstrument.renderers.base import Renderer
10 from pyinstrument.renderers.console import ConsoleRenderer
11 from pyinstrument.typing import Unpack
12 from pyinstrument.util import file_supports_color, file_supports_unicode
13
14 CallableVar = typing.TypeVar("CallableVar", bound=typing.Callable)
15
16
17 class ProfileContextOptions(typing.TypedDict, total=False):
18 interval: float
19 async_mode: AsyncMode
20 use_timing_thread: bool | None
21 renderer: Renderer | None
22 target_description: str | None
23
24
25 class ProfileContext:
26 options: ProfileContextOptions
27
28 def __init__(
29 self,
30 **kwargs: Unpack[ProfileContextOptions],
31 ):
32 profiler_options = {
33 "interval": kwargs.get("interval", 0.001),
34 # note- different async mode from the default, because it's easy
35 # to run multiple profilers at once using the decorator/context
36 # manager
37 "async_mode": kwargs.get("async_mode", "disabled"),
38 "use_timing_thread": kwargs.get("use_timing_thread", None),
39 }
40 self.profiler = Profiler(**profiler_options)
41 self.options = kwargs
42
43 @typing.overload
44 def __call__(self, func: CallableVar, /) -> CallableVar: ...
45 @typing.overload
46 def __call__(self, /, **kwargs: Unpack[ProfileContextOptions]) -> "ProfileContext": ...
47 def __call__(
48 self, func: typing.Callable | None = None, /, **kwargs: Unpack[ProfileContextOptions]
49 ):
50 if func is not None:
51
52 @functools.wraps(func)
53 def wrapper(*args, **kwargs):
54 target_description = self.options.get("target_description")
55 if target_description is None:
56 target_description = f"Function {func.__qualname__} at {func.__code__.co_filename}:{func.__code__.co_firstlineno}"
57
58 with self(target_description=target_description):
59 return func(*args, **kwargs)
60
61 return typing.cast(typing.Callable, wrapper)
62 else:
63 return ProfileContext(**{**self.options, **kwargs})
64
65 def __enter__(self):
66 if self.profiler.is_running:
67 raise RuntimeError(
68 "This profiler is already running - did you forget the brackets on pyinstrument.profile() ?"
69 )
70
71 caller_frame = inspect.currentframe().f_back # type: ignore
72 assert caller_frame is not None
73 target_description = self.options.get("target_description")
74 if target_description is None:
75 target_description = "Block at {}:{}".format(
76 caller_frame.f_code.co_filename, caller_frame.f_lineno
77 )
78
79 self.profiler.start(
80 caller_frame=caller_frame,
81 target_description=target_description,
82 )
83
84 def __exit__(self, exc_type, exc_value, traceback):
85 session = self.profiler.stop()
86
87 renderer = self.options.get("renderer")
88 f = sys.stderr
89
90 if renderer is None:
91 renderer = ConsoleRenderer(
92 color=file_supports_color(f),
93 unicode=file_supports_unicode(f),
94 short_mode=True,
95 )
96
97 f.write(renderer.render(session))
98
99
100 class _Profile:
101 @typing.overload
102 def __call__(self, func: CallableVar, /) -> CallableVar: ...
103 @typing.overload
104 def __call__(self, /, **kwargs: Unpack[ProfileContextOptions]) -> "ProfileContext": ...
105 def __call__(
106 self, func: typing.Callable | None = None, /, **kwargs: Unpack[ProfileContextOptions]
107 ):
108 if func is not None:
109 return ProfileContext(**kwargs)(func)
110 else:
111 return ProfileContext(**kwargs)
112
113
114 profile = _Profile()