22
33import contextlib
44import inspect
5+
6+ # System Imports
57import logging
68import os
79import platform
810import re
911import sys
1012import time as _time_module
1113import warnings
12-
13- # System Imports
1414from pathlib import Path
1515from typing import TYPE_CHECKING , Any , Callable , Optional
1616from unittest import TestCase
1717
18+ # PyTest Imports
1819import pytest
1920from pluggy import HookspecMarker
2021
2324 STABILITY_SPREAD_TOLERANCE ,
2425 STABILITY_WINDOW_SIZE ,
2526)
26-
27- # PyTest Imports
2827from codeflash .result .best_summed_runtime import calculate_best_summed_runtime
2928
3029if TYPE_CHECKING :
@@ -293,11 +292,14 @@ def get_runtime_from_stdout(stdout: str) -> Optional[int]:
293292 return None
294293
295294 payload = stdout [start + len (marker_start ) : end ]
296- last_colon = payload .rfind (":" )
297- if last_colon == - 1 :
295+ parts = payload .split (":" )
296+ if len ( parts ) != 6 :
298297 return None
299298
300- return int (payload [last_colon + 1 :])
299+ try :
300+ return int (parts [5 ])
301+ except ValueError :
302+ return None
301303
302304
303305_NODEID_BRACKET_PATTERN = re .compile (r"\s*\[\s*\d+\s*\]\s*$" )
@@ -312,12 +314,11 @@ def should_stop(
312314 if len (runtimes ) < window :
313315 return False
314316
317+ # runtimes is already sorted descending
315318 recent = runtimes [- window :]
316319
317- # Use sorted array for faster median and min/max operations
318- recent_sorted = sorted (recent )
319320 mid = window // 2
320- m = recent_sorted [mid ] if window % 2 else (recent_sorted [mid - 1 ] + recent_sorted [mid ]) / 2
321+ m = recent [mid ] if window % 2 else (recent [mid - 1 ] + recent [mid ]) / 2
321322
322323 # 1) All recent points close to the median
323324 centered = True
@@ -327,7 +328,8 @@ def should_stop(
327328 break
328329
329330 # 2) Window spread is small
330- r_min , r_max = recent_sorted [0 ], recent_sorted [- 1 ]
331+ r_max = recent [0 ]
332+ r_min = recent [- 1 ]
331333 spread_ok = (r_max - r_min ) / r_min <= spread_rel_tol
332334
333335 return centered and spread_ok
@@ -406,7 +408,8 @@ def pytest_runtestloop(self, session: Session) -> bool:
406408 estimated_total_loops = 0
407409 if elapsed > 0 :
408410 rate = count / elapsed # loops / nano-seconds
409- estimated_total_loops = int (rate * total_time * 1e9 )
411+ total_time_ns = total_time * 1e9
412+ estimated_total_loops = int (rate * total_time_ns )
410413
411414 window_size = int (STABILITY_WINDOW_SIZE * estimated_total_loops + 0.5 )
412415 if (
0 commit comments