|
| 1 | +import time |
| 2 | +from typing import Callable |
| 3 | +from typing import Generator |
| 4 | + |
| 5 | +import bm |
| 6 | +import bm.utils as utils |
| 7 | + |
| 8 | +from ddtrace.trace import tracer |
| 9 | + |
| 10 | + |
| 11 | +class RecursiveComputation(bm.Scenario): |
| 12 | + name: str |
| 13 | + max_depth: int |
| 14 | + enable_sleep: bool |
| 15 | + sleep_duration: float |
| 16 | + profiler_enabled: bool |
| 17 | + |
| 18 | + def cpu_intensive_computation(self, depth: int) -> int: |
| 19 | + limit = 100 + (depth * 10) |
| 20 | + primes = [] |
| 21 | + |
| 22 | + for num in range(2, limit): |
| 23 | + is_prime = True |
| 24 | + for i in range(2, int(num**0.5) + 1): |
| 25 | + if num % i == 0: |
| 26 | + is_prime = False |
| 27 | + break |
| 28 | + |
| 29 | + if is_prime: |
| 30 | + primes.append(num) |
| 31 | + |
| 32 | + return len(primes) |
| 33 | + |
| 34 | + def recursive_traced_computation(self, depth: int = 0) -> int: |
| 35 | + with tracer.trace(f"recursive_computation.depth_{depth}") as span: |
| 36 | + span.set_tag("recursion.depth", depth) |
| 37 | + span.set_tag("recursion.max_depth", self.max_depth) |
| 38 | + span.set_tag("profiler.enabled", self.profiler_enabled) |
| 39 | + span.set_tag("component", "recursive_computation") |
| 40 | + |
| 41 | + if depth % 3 == 0: |
| 42 | + start_time = time.time() |
| 43 | + result = self.cpu_intensive_computation(depth) |
| 44 | + compute_time = time.time() - start_time |
| 45 | + |
| 46 | + span.set_metric("computation.time_ms", compute_time * 1000) |
| 47 | + span.set_metric("computation.result", result) |
| 48 | + else: |
| 49 | + result = depth |
| 50 | + span.set_metric("computation.time_ms", 0) |
| 51 | + span.set_metric("computation.result", result) |
| 52 | + |
| 53 | + if depth < self.max_depth: |
| 54 | + child_result = self.recursive_traced_computation(depth + 1) |
| 55 | + span.set_metric("child.result", child_result) |
| 56 | + result += child_result |
| 57 | + elif self.enable_sleep: |
| 58 | + span.set_tag("action", "sleep_at_max_depth") |
| 59 | + time.sleep(self.sleep_duration) |
| 60 | + |
| 61 | + span.set_metric("final.result", result) |
| 62 | + return result |
| 63 | + |
| 64 | + def run(self) -> Generator[Callable[[int], None], None, None]: |
| 65 | + if self.profiler_enabled: |
| 66 | + import ddtrace.profiling.auto # noqa: F401 |
| 67 | + |
| 68 | + utils.drop_traces(tracer) |
| 69 | + utils.drop_telemetry_events() |
| 70 | + |
| 71 | + def _(loops: int) -> None: |
| 72 | + for _ in range(loops): |
| 73 | + self.recursive_traced_computation() |
| 74 | + |
| 75 | + yield _ |
0 commit comments