| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import sys |
| 5 |
import textwrap |
| 6 |
import threading |
| 7 |
import timeit |
| 8 |
import types |
| 9 |
from contextvars import ContextVar |
| 10 |
from typing import Any, Callable, List, NamedTuple, Optional |
| 11 |
|
| 12 |
from pyinstrument.low_level.stat_profile import ( |
| 13 |
get_frame_info, |
| 14 |
measure_timing_overhead, |
| 15 |
setstatprofile, |
| 16 |
walltime_coarse_resolution, |
| 17 |
) |
| 18 |
from pyinstrument.low_level.types import TimerType |
| 19 |
from pyinstrument.typing import LiteralStr |
| 20 |
from pyinstrument.util import format_float_with_sig_figs, strtobool, unwrap |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
thread_locals = threading.local() |
| 26 |
|
| 27 |
StackSamplerSubscriberTarget = Callable[[List[str], float, Optional["AsyncState"]], None] |
| 28 |
|
| 29 |
IGNORE_OVERHEAD_WARNING = strtobool(os.environ.get("PYINSTRUMENT_IGNORE_OVERHEAD_WARNING", "0")) |
| 30 |
|
| 31 |
|
| 32 |
class StackSamplerSubscriber: |
| 33 |
def __init__( |
| 34 |
self, |
| 35 |
*, |
| 36 |
target: StackSamplerSubscriberTarget, |
| 37 |
desired_interval: float, |
| 38 |
bound_to_async_context: bool, |
| 39 |
async_state: AsyncState | None, |
| 40 |
use_timing_thread: bool | None = None, |
| 41 |
) -> None: |
| 42 |
self.target = target |
| 43 |
self.desired_interval = desired_interval |
| 44 |
self.use_timing_thread = use_timing_thread |
| 45 |
self.bound_to_async_context = bound_to_async_context |
| 46 |
self.async_state = async_state |
| 47 |
|
| 48 |
|
| 49 |
active_profiler_context_var: ContextVar[object | None] = ContextVar( |
| 50 |
"active_profiler_context_var", default=None |
| 51 |
) |
| 52 |
|
| 53 |
|
| 54 |
class StackSampler: |
| 55 |
"""Manages setstatprofile for Profilers on a single thread""" |
| 56 |
|
| 57 |
subscribers: list[StackSamplerSubscriber] |
| 58 |
current_sampling_interval: float | None |
| 59 |
last_profile_time: float |
| 60 |
timer_func: Callable[[], float] | None |
| 61 |
has_warned_about_timing_overhead: bool |
| 62 |
|
| 63 |
def __init__(self) -> None: |
| 64 |
self.subscribers = [] |
| 65 |
self.current_sampling_interval = None |
| 66 |
self.last_profile_time = 0.0 |
| 67 |
self.timer_func = None |
| 68 |
self.has_warned_about_timing_overhead = False |
| 69 |
|
| 70 |
def subscribe( |
| 71 |
self, |
| 72 |
target: StackSamplerSubscriberTarget, |
| 73 |
*, |
| 74 |
desired_interval: float, |
| 75 |
use_timing_thread: bool | None = None, |
| 76 |
use_async_context: bool, |
| 77 |
): |
| 78 |
if use_async_context: |
| 79 |
if active_profiler_context_var.get() is not None: |
| 80 |
raise RuntimeError( |
| 81 |
"There is already a profiler running. You cannot run multiple profilers in the same thread or async context, unless you disable async support." |
| 82 |
) |
| 83 |
active_profiler_context_var.set(target) |
| 84 |
|
| 85 |
existing_subscriber = next((s for s in self.subscribers if s.target == target), None) |
| 86 |
if existing_subscriber is not None: |
| 87 |
raise ValueError("This target is already subscribed to the stack sampler.") |
| 88 |
|
| 89 |
self.subscribers.append( |
| 90 |
StackSamplerSubscriber( |
| 91 |
target=target, |
| 92 |
desired_interval=desired_interval, |
| 93 |
use_timing_thread=use_timing_thread, |
| 94 |
bound_to_async_context=use_async_context, |
| 95 |
async_state=AsyncState("in_context") if use_async_context else None, |
| 96 |
) |
| 97 |
) |
| 98 |
self._update() |
| 99 |
|
| 100 |
def unsubscribe(self, target: StackSamplerSubscriberTarget): |
| 101 |
try: |
| 102 |
subscriber = next(s for s in self.subscribers if s.target == target) |
| 103 |
except StopIteration: |
| 104 |
raise StackSampler.SubscriberNotFound() |
| 105 |
|
| 106 |
if subscriber.bound_to_async_context: |
| 107 |
|
| 108 |
|
| 109 |
active_profiler_context_var.set(None) |
| 110 |
|
| 111 |
self.subscribers.remove(subscriber) |
| 112 |
|
| 113 |
self._update() |
| 114 |
|
| 115 |
def _update(self): |
| 116 |
if len(self.subscribers) == 0: |
| 117 |
self._stop_sampling() |
| 118 |
return |
| 119 |
|
| 120 |
min_subscribers_interval = min(s.desired_interval for s in self.subscribers) |
| 121 |
timing_thread_preferences = set( |
| 122 |
s.use_timing_thread for s in self.subscribers if s.use_timing_thread is not None |
| 123 |
) |
| 124 |
if len(timing_thread_preferences) > 1: |
| 125 |
raise ValueError( |
| 126 |
f"Profiler requested different timing thread preferences from a profiler that is already running." |
| 127 |
) |
| 128 |
|
| 129 |
use_timing_thread = next(iter(timing_thread_preferences), False) |
| 130 |
|
| 131 |
if self.current_sampling_interval != min_subscribers_interval: |
| 132 |
self._start_sampling( |
| 133 |
interval=min_subscribers_interval, use_timing_thread=use_timing_thread |
| 134 |
) |
| 135 |
|
| 136 |
def _start_sampling(self, interval: float, use_timing_thread: bool): |
| 137 |
if use_timing_thread and self.timer_func is not None: |
| 138 |
raise ValueError( |
| 139 |
f"Profiler requested to use the timing thread but this stack sampler is already using a custom timer function." |
| 140 |
) |
| 141 |
|
| 142 |
timer_type: TimerType |
| 143 |
|
| 144 |
if self.timer_func: |
| 145 |
timer_type = "timer_func" |
| 146 |
elif use_timing_thread: |
| 147 |
timer_type = "walltime_thread" |
| 148 |
else: |
| 149 |
coarse_resolution = walltime_coarse_resolution() |
| 150 |
if coarse_resolution is not None and coarse_resolution <= interval: |
| 151 |
timer_type = "walltime_coarse" |
| 152 |
else: |
| 153 |
timer_type = "walltime" |
| 154 |
|
| 155 |
self._check_timing_overhead(interval=interval, timer_type=timer_type) |
| 156 |
|
| 157 |
self.current_sampling_interval = interval |
| 158 |
if self.last_profile_time == 0.0: |
| 159 |
self.last_profile_time = self._timer() |
| 160 |
|
| 161 |
setstatprofile( |
| 162 |
target=self._sample, |
| 163 |
interval=interval, |
| 164 |
context_var=active_profiler_context_var, |
| 165 |
timer_type=timer_type, |
| 166 |
timer_func=self.timer_func, |
| 167 |
) |
| 168 |
|
| 169 |
def _stop_sampling(self): |
| 170 |
setstatprofile(None) |
| 171 |
self.current_sampling_interval = None |
| 172 |
self.last_profile_time = 0.0 |
| 173 |
|
| 174 |
def _sample(self, frame: types.FrameType, event: str, arg: Any): |
| 175 |
if event == "context_changed": |
| 176 |
new, old, coroutine_stack = arg |
| 177 |
|
| 178 |
for subscriber in self.subscribers: |
| 179 |
if subscriber.target == old: |
| 180 |
assert subscriber.bound_to_async_context |
| 181 |
full_stack = build_call_stack(frame, event, arg) |
| 182 |
if coroutine_stack: |
| 183 |
full_stack.extend(reversed(coroutine_stack)) |
| 184 |
subscriber.async_state = AsyncState( |
| 185 |
"out_of_context_awaited", info=full_stack |
| 186 |
) |
| 187 |
else: |
| 188 |
subscriber.async_state = AsyncState( |
| 189 |
"out_of_context_unknown", info=full_stack |
| 190 |
) |
| 191 |
elif subscriber.target == new: |
| 192 |
assert subscriber.bound_to_async_context |
| 193 |
subscriber.async_state = AsyncState("in_context") |
| 194 |
else: |
| 195 |
now = self._timer() |
| 196 |
time_since_last_sample = now - self.last_profile_time |
| 197 |
|
| 198 |
call_stack = build_call_stack(frame, event, arg) |
| 199 |
|
| 200 |
for subscriber in self.subscribers: |
| 201 |
subscriber.target(call_stack, time_since_last_sample, subscriber.async_state) |
| 202 |
|
| 203 |
self.last_profile_time = now |
| 204 |
|
| 205 |
def _timer(self): |
| 206 |
if self.timer_func: |
| 207 |
return self.timer_func() |
| 208 |
else: |
| 209 |
return timeit.default_timer() |
| 210 |
|
| 211 |
def _check_timing_overhead(self, interval: float, timer_type: TimerType): |
| 212 |
if self.has_warned_about_timing_overhead: |
| 213 |
return |
| 214 |
if IGNORE_OVERHEAD_WARNING: |
| 215 |
return |
| 216 |
|
| 217 |
overheads = timing_overhead() |
| 218 |
overhead = overheads.get(timer_type) |
| 219 |
if overhead is None: |
| 220 |
return |
| 221 |
|
| 222 |
if timer_type == "walltime": |
| 223 |
if overhead > 300e-9: |
| 224 |
self.has_warned_about_timing_overhead = True |
| 225 |
message_parts: list[str] = [] |
| 226 |
message_parts.append( |
| 227 |
f""" |
| 228 |
pyinstrument: the timer on your system has an overhead of |
| 229 |
{overhead * 1e9:.0f} nanoseconds, which is considered |
| 230 |
high. You might experience longer runtimes than usual, and |
| 231 |
programs with lots of pure-python code might be distorted. |
| 232 |
""" |
| 233 |
) |
| 234 |
|
| 235 |
message_parts.append( |
| 236 |
f""" |
| 237 |
You might want to try the timing thread option, which can |
| 238 |
be enabled using --use-timing-thread at the command line, |
| 239 |
or by setting the use_timing_thread parameter in the |
| 240 |
Profiler constructor. |
| 241 |
""" |
| 242 |
) |
| 243 |
|
| 244 |
if "walltime_coarse" in overheads and overheads["walltime_coarse"] < 300e-9: |
| 245 |
coarse_resolution = walltime_coarse_resolution() |
| 246 |
assert coarse_resolution is not None |
| 247 |
message_parts.append( |
| 248 |
f""" |
| 249 |
Your system does offer a 'coarse' timer, with a lower |
| 250 |
overhead ({overheads["walltime_coarse"] * 1e9:.2g} |
| 251 |
nanoseconds). You can enable it by setting |
| 252 |
pyinstrument's interval to a value higher than |
| 253 |
{format_float_with_sig_figs(coarse_resolution, |
| 254 |
trim_zeroes=True)} seconds. If you're happy with the |
| 255 |
lower precision, this is the best option. |
| 256 |
""" |
| 257 |
) |
| 258 |
|
| 259 |
message_parts.append( |
| 260 |
f""" |
| 261 |
If you want to suppress this warning, you can set the |
| 262 |
environment variable PYINSTRUMENT_IGNORE_OVERHEAD_WARNING |
| 263 |
to '1'. |
| 264 |
""" |
| 265 |
) |
| 266 |
|
| 267 |
message = "\n\n".join( |
| 268 |
textwrap.fill(unwrap(part), width=80) for part in message_parts |
| 269 |
) |
| 270 |
|
| 271 |
print(message, file=sys.stderr) |
| 272 |
|
| 273 |
class SubscriberNotFound(Exception): |
| 274 |
pass |
| 275 |
|
| 276 |
|
| 277 |
def get_stack_sampler() -> StackSampler: |
| 278 |
""" |
| 279 |
Gets the stack sampler for the current thread, creating it if necessary |
| 280 |
""" |
| 281 |
try: |
| 282 |
return thread_locals.stack_sampler |
| 283 |
except AttributeError: |
| 284 |
|
| 285 |
stack_sampler = StackSampler() |
| 286 |
thread_locals.stack_sampler = stack_sampler |
| 287 |
return stack_sampler |
| 288 |
|
| 289 |
|
| 290 |
def build_call_stack(frame: types.FrameType | None, event: str, arg: Any) -> list[str]: |
| 291 |
call_stack: list[str] = [] |
| 292 |
|
| 293 |
if event == "call": |
| 294 |
|
| 295 |
|
| 296 |
frame = frame.f_back if frame else None |
| 297 |
elif event == "c_return" or event == "c_exception": |
| 298 |
|
| 299 |
|
| 300 |
c_frame_identifier = "%s\x00%s\x00%i" % ( |
| 301 |
getattr(arg, "__qualname__", arg.__name__), |
| 302 |
"<built-in>", |
| 303 |
0, |
| 304 |
) |
| 305 |
call_stack.append(c_frame_identifier) |
| 306 |
|
| 307 |
while frame is not None: |
| 308 |
call_stack.append(get_frame_info(frame)) |
| 309 |
frame = frame.f_back |
| 310 |
|
| 311 |
thread = threading.current_thread() |
| 312 |
thread_identifier = "%s\x00%s\x00%i" % (thread.name, "<thread>", thread.ident) |
| 313 |
call_stack.append(thread_identifier) |
| 314 |
|
| 315 |
|
| 316 |
|
| 317 |
call_stack.reverse() |
| 318 |
|
| 319 |
return call_stack |
| 320 |
|
| 321 |
|
| 322 |
class AsyncState(NamedTuple): |
| 323 |
state: LiteralStr["in_context", "out_of_context_awaited", "out_of_context_unknown"] |
| 324 |
""" |
| 325 |
Definitions: |
| 326 |
``in_context``: indicates that the sample comes from the subscriber's |
| 327 |
context. |
| 328 |
|
| 329 |
``out_of_context_awaited``: the sample comes from outside the |
| 330 |
subscriber's context, but we tracked the await that happened before the |
| 331 |
context exited. :attr:`info` contains the call stack of the await. |
| 332 |
|
| 333 |
``out_of_context_unknown``: the sample comes from outside the |
| 334 |
subscriber's context, but the change of context didn't look like an |
| 335 |
await. :attr:`info` contains the call stack when the context changed. |
| 336 |
""" |
| 337 |
|
| 338 |
info: Any = None |
| 339 |
|
| 340 |
|
| 341 |
_timing_overhead: dict[TimerType, float] | None = None |
| 342 |
|
| 343 |
|
| 344 |
def timing_overhead() -> dict[TimerType, float]: |
| 345 |
global _timing_overhead |
| 346 |
if _timing_overhead is None: |
| 347 |
_timing_overhead = measure_timing_overhead() |
| 348 |
return _timing_overhead |