Skip to content

Commit f71a8f4

Browse files
authored
fix(profiling): Dynamically adjust profiler sleep time (#1634)
Because more time may have elapsed between 2 samples due to us calling the sampling function and other threads executing, we need to account for it in the sleep or the time between samples will often be greater than the expected interval. This change ensures we account for this time elapsed and dynamically adjust the amount of time we sleep for between samples.
1 parent b6c0096 commit f71a8f4

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

sentry_sdk/profiler.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -377,10 +377,23 @@ class _SleepScheduler(_ThreadScheduler):
377377

378378
def run(self):
379379
# type: () -> None
380+
last = time.perf_counter()
381+
380382
while True:
383+
# some time may have elapsed since the last time
384+
# we sampled, so we need to account for that and
385+
# not sleep for too long
386+
now = time.perf_counter()
387+
elapsed = max(now - last, 0)
388+
389+
if elapsed < self._interval:
390+
time.sleep(self._interval - elapsed)
391+
392+
last = time.perf_counter()
393+
381394
if self.event.is_set():
382395
break
383-
time.sleep(self._interval)
396+
384397
_sample_stack()
385398

386399

@@ -395,9 +408,11 @@ class _EventScheduler(_ThreadScheduler):
395408
def run(self):
396409
# type: () -> None
397410
while True:
411+
self.event.wait(timeout=self._interval)
412+
398413
if self.event.is_set():
399414
break
400-
self.event.wait(timeout=self._interval)
415+
401416
_sample_stack()
402417

403418

0 commit comments

Comments
 (0)