|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING |
| 4 | + |
| 5 | +from codeflash.cli_cmds.console import console, logger |
| 6 | +from codeflash.code_utils.config_consts import DEFAULT_IMPORTANCE_THRESHOLD |
| 7 | +from codeflash.discovery.functions_to_optimize import FunctionToOptimize |
| 8 | +from codeflash.tracing.profile_stats import ProfileStats |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from pathlib import Path |
| 12 | + |
| 13 | + from codeflash.discovery.functions_to_optimize import FunctionToOptimize |
| 14 | + |
| 15 | + |
| 16 | +class FunctionRanker: |
| 17 | + """Ranks and filters functions based on a ttX score derived from profiling data. |
| 18 | +
|
| 19 | + The ttX score is calculated as: |
| 20 | + ttX = own_time + (time_spent_in_callees / call_count) |
| 21 | +
|
| 22 | + This score prioritizes functions that are computationally heavy themselves (high `own_time`) |
| 23 | + or that make expensive calls to other functions (high average `time_spent_in_callees`). |
| 24 | +
|
| 25 | + Functions are first filtered by an importance threshold based on their `own_time` as a |
| 26 | + fraction of the total runtime. The remaining functions are then ranked by their ttX score |
| 27 | + to identify the best candidates for optimization. |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__(self, trace_file_path: Path) -> None: |
| 31 | + self.trace_file_path = trace_file_path |
| 32 | + self._profile_stats = ProfileStats(trace_file_path.as_posix()) |
| 33 | + self._function_stats: dict[str, dict] = {} |
| 34 | + self.load_function_stats() |
| 35 | + |
| 36 | + def load_function_stats(self) -> None: |
| 37 | + try: |
| 38 | + for (filename, line_number, func_name), ( |
| 39 | + call_count, |
| 40 | + _num_callers, |
| 41 | + total_time_ns, |
| 42 | + cumulative_time_ns, |
| 43 | + _callers, |
| 44 | + ) in self._profile_stats.stats.items(): |
| 45 | + if call_count <= 0: |
| 46 | + continue |
| 47 | + |
| 48 | + # Parse function name to handle methods within classes |
| 49 | + class_name, qualified_name, base_function_name = (None, func_name, func_name) |
| 50 | + if "." in func_name and not func_name.startswith("<"): |
| 51 | + parts = func_name.split(".", 1) |
| 52 | + if len(parts) == 2: |
| 53 | + class_name, base_function_name = parts |
| 54 | + |
| 55 | + # Calculate own time (total time - time spent in subcalls) |
| 56 | + own_time_ns = total_time_ns |
| 57 | + time_in_callees_ns = cumulative_time_ns - total_time_ns |
| 58 | + |
| 59 | + # Calculate ttX score |
| 60 | + ttx_score = own_time_ns + (time_in_callees_ns / call_count) |
| 61 | + |
| 62 | + function_key = f"{filename}:{qualified_name}" |
| 63 | + self._function_stats[function_key] = { |
| 64 | + "filename": filename, |
| 65 | + "function_name": base_function_name, |
| 66 | + "qualified_name": qualified_name, |
| 67 | + "class_name": class_name, |
| 68 | + "line_number": line_number, |
| 69 | + "call_count": call_count, |
| 70 | + "own_time_ns": own_time_ns, |
| 71 | + "cumulative_time_ns": cumulative_time_ns, |
| 72 | + "time_in_callees_ns": time_in_callees_ns, |
| 73 | + "ttx_score": ttx_score, |
| 74 | + } |
| 75 | + |
| 76 | + logger.debug(f"Loaded timing stats for {len(self._function_stats)} functions from trace using ProfileStats") |
| 77 | + |
| 78 | + except Exception as e: |
| 79 | + logger.warning(f"Failed to process function stats from trace file {self.trace_file_path}: {e}") |
| 80 | + self._function_stats = {} |
| 81 | + |
| 82 | + def _get_function_stats(self, function_to_optimize: FunctionToOptimize) -> dict | None: |
| 83 | + target_filename = function_to_optimize.file_path.name |
| 84 | + for key, stats in self._function_stats.items(): |
| 85 | + if stats.get("function_name") == function_to_optimize.function_name and ( |
| 86 | + key.endswith(f"/{target_filename}") or target_filename in key |
| 87 | + ): |
| 88 | + return stats |
| 89 | + |
| 90 | + logger.debug( |
| 91 | + f"Could not find stats for function {function_to_optimize.function_name} in file {target_filename}" |
| 92 | + ) |
| 93 | + return None |
| 94 | + |
| 95 | + def get_function_ttx_score(self, function_to_optimize: FunctionToOptimize) -> float: |
| 96 | + stats = self._get_function_stats(function_to_optimize) |
| 97 | + return stats["ttx_score"] if stats else 0.0 |
| 98 | + |
| 99 | + def rank_functions(self, functions_to_optimize: list[FunctionToOptimize]) -> list[FunctionToOptimize]: |
| 100 | + ranked = sorted(functions_to_optimize, key=self.get_function_ttx_score, reverse=True) |
| 101 | + logger.debug( |
| 102 | + f"Function ranking order: {[f'{func.function_name} (ttX={self.get_function_ttx_score(func):.2f})' for func in ranked]}" |
| 103 | + ) |
| 104 | + return ranked |
| 105 | + |
| 106 | + def get_function_stats_summary(self, function_to_optimize: FunctionToOptimize) -> dict | None: |
| 107 | + return self._get_function_stats(function_to_optimize) |
| 108 | + |
| 109 | + def rerank_functions(self, functions_to_optimize: list[FunctionToOptimize]) -> list[FunctionToOptimize]: |
| 110 | + """Ranks functions based on their ttX score. |
| 111 | +
|
| 112 | + This method calculates the ttX score for each function and returns |
| 113 | + the functions sorted in descending order of their ttX score. |
| 114 | + """ |
| 115 | + if not self._function_stats: |
| 116 | + logger.warning("No function stats available to rank functions.") |
| 117 | + return [] |
| 118 | + |
| 119 | + return self.rank_functions(functions_to_optimize) |
| 120 | + |
| 121 | + def rerank_and_filter_functions(self, functions_to_optimize: list[FunctionToOptimize]) -> list[FunctionToOptimize]: |
| 122 | + """Reranks and filters functions based on their impact on total runtime. |
| 123 | +
|
| 124 | + This method first calculates the total runtime of all profiled functions. |
| 125 | + It then filters out functions whose own_time is less than a specified |
| 126 | + percentage of the total runtime (importance_threshold). |
| 127 | +
|
| 128 | + The remaining 'important' functions are then ranked by their ttX score. |
| 129 | + """ |
| 130 | + stats_map = self._function_stats |
| 131 | + if not stats_map: |
| 132 | + return [] |
| 133 | + |
| 134 | + total_program_time = sum(s["own_time_ns"] for s in stats_map.values() if s.get("own_time_ns", 0) > 0) |
| 135 | + |
| 136 | + if total_program_time == 0: |
| 137 | + logger.warning("Total program time is zero, cannot determine function importance.") |
| 138 | + return self.rank_functions(functions_to_optimize) |
| 139 | + |
| 140 | + important_functions = [] |
| 141 | + for func in functions_to_optimize: |
| 142 | + func_stats = self._get_function_stats(func) |
| 143 | + if func_stats and func_stats.get("own_time_ns", 0) > 0: |
| 144 | + importance = func_stats["own_time_ns"] / total_program_time |
| 145 | + if importance >= DEFAULT_IMPORTANCE_THRESHOLD: |
| 146 | + important_functions.append(func) |
| 147 | + else: |
| 148 | + logger.debug( |
| 149 | + f"Filtering out function {func.qualified_name} with importance " |
| 150 | + f"{importance:.2%} (below threshold {DEFAULT_IMPORTANCE_THRESHOLD:.2%})" |
| 151 | + ) |
| 152 | + |
| 153 | + logger.info( |
| 154 | + f"Filtered down to {len(important_functions)} important functions from {len(functions_to_optimize)} total functions" |
| 155 | + ) |
| 156 | + console.rule() |
| 157 | + |
| 158 | + return self.rank_functions(important_functions) |
0 commit comments