| 1 | import cProfile |
| 2 | import io |
| 3 | import pstats |
| 4 | import sys |
| 5 | from pathlib import Path |
| 6 | |
| 7 | import pytest |
| 8 | |
| 9 | PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| 10 | if str(PROJECT_ROOT) not in sys.path: |
| 11 | sys.path.insert(0, str(PROJECT_ROOT)) |
| 12 | |
| 13 | from agent import Agent, AgentContext |
| 14 | from helpers.extension import extensible |
| 15 | from initialize import initialize_agent |
| 16 | |
| 17 | |
| 18 | class PerfAgent(Agent): |
| 19 | @extensible |
| 20 | def perf_hook(self, value: int): |
| 21 | return value + 1 |
| 22 | |
| 23 | |
| 24 | @pytest.mark.parametrize("iterations", [10000]) |
| 25 | def test_extensible_method_performance_trace(iterations: int): |
| 26 | agent = PerfAgent(number=0, config=initialize_agent()) |
| 27 | context = agent.context |
| 28 | |
| 29 | try: |
| 30 | profiler = cProfile.Profile() |
| 31 | profiler.enable() |
| 32 | |
| 33 | result = 0 |
| 34 | for i in range(iterations): |
| 35 | result = agent.perf_hook(i) |
| 36 | |
| 37 | profiler.disable() |
| 38 | |
| 39 | output = io.StringIO() |
| 40 | stats = pstats.Stats(profiler, stream=output) |
| 41 | stats.sort_stats("cumulative") |
| 42 | stats.print_stats(20) |
| 43 | |
| 44 | print(f"\n[extensible perf] iterations={iterations} result={result}") |
| 45 | print(output.getvalue()) |
| 46 | |
| 47 | assert result == iterations |
| 48 | finally: |
| 49 | if context: |
| 50 | AgentContext.remove(context.id) |