2121import importlib .util
2222import timeit
2323from pathlib import Path
24+ from textwrap import dedent
2425
2526import click
2627
@@ -83,6 +84,25 @@ def _load_scenario_module(scenario_file):
8384 return scenario_name , module
8485
8586
87+ def _get_scenario_source_code (scenario_name ):
88+ """Get the file path for a scenario by name."""
89+ scenarios_dir = Path (__file__ ).parent / "scenarios"
90+ scenario_file = scenarios_dir / f"{ scenario_name } .py"
91+ if not scenario_file .exists ():
92+ click .echo (f"Error: Could not find scenario file for '{ scenario_name } '" , err = True )
93+ raise click .Abort ()
94+ with open (scenario_file ) as f :
95+ scenario_source = f .read ()
96+
97+ setup_code = dedent (
98+ scenario_source +
99+ "context = setup()"
100+ )
101+ stmt_code = "run(context)"
102+ return dedent (setup_code ), stmt_code
103+
104+
105+
86106def create_scenario_runner (scenario_module ):
87107 """
88108 Create a callable that sets up the scenario once and runs it.
@@ -153,11 +173,9 @@ def run(label, scenario):
153173 click .echo (err_msg , err = True )
154174 raise click .Abort ()
155175
156- scenario_module = scenarios [scenario ]
157-
158176 try :
159- runner = create_scenario_runner ( scenario_module )
160- result = timeit .timeit (runner , number = 1 )
177+ setup_code , stmt_code = _get_scenario_source_code ( scenario )
178+ result = timeit .timeit (stmt_code , setup = setup_code , number = 1 )
161179
162180 # Output in TSV format: LABEL RESULT
163181 print (f"{ label } \t { result } " ) # noqa
0 commit comments