From 4fc067e3bf64f1393df1d3bdd611e3aa7c37173b Mon Sep 17 00:00:00 2001 From: TermiNexus Date: Tue, 29 Sep 2026 14:36:57 +0800 Subject: [PATCH] =?UTF-8?q?perf(tpc):=20=E6=8C=89=20profile=20=E6=B6=88?= =?UTF-8?q?=E6=8E=89=E4=B8=A4=E5=A4=84=E4=B8=BB=E7=83=AD=E7=82=B9=EF=BC=88?= =?UTF-8?q?stub=20=E7=B4=A2=E5=BC=95=E6=AF=8F=20miss=20=E9=87=8D=E6=89=AB?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=20/=20vtable=20=E6=AF=8F=E7=B1=BB=E5=85=A8?= =?UTF-8?q?=E6=89=AB=E5=87=BD=E6=95=B0=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 依据 PROF/main_prof_10152.prof(main_time.txt: 失败 2362.46s,72 个文件全部走 顺序 _translate_file,tottime 合计 2288.9s): tottime calls 函数 491.7s 723782 nt._path_isdir ← 总时长 21% 268.6s 15762 StructGen._generate_structs 182.9s 479819 nt.listdir ← 8% 87.2s 657640754 builtins.isinstance 78.6s 41514263 ntpath.join 75.9s 83047878 ntpath.splitroot 75.7s 1631 StructGen._create_Vtable_globals (46ms/次) 66.6s 238007 HandlesImports._build_stub_index 63.0s 317868145 str.startswith 38.4s 175751378 str.endswith ... ── 仅 isdir + listdir + join/splitroot/endswith ≈ 850s ≈ 总时长的 37% 一、_build_stub_index 的零 syscall 快路径(HandlesImports + Phase2Translator) 它由 _TryLoadStructFromStub 的**每次索引 miss** 调用(238k 次),每次都要 2× os.path.isdir + 2× os.listdir + 全量 endswith/join 重拼文件集合 —— 这正是上面 isdir 723k / listdir 479k 的主要来源。 改为:写入方显式置脏(ImportHandle.MarkStubSetDirty),未置脏时直接返回。 置脏点:① 每个文件翻译入口(_translate_file,顺序与 worker 模式皆按文件粒度 覆盖)② 写 temp/.stub.ll 之后 ③ 注册 include 写 output/.stub.ll 之后。索引建完即清脏。语义:增量重扫、output 覆盖 temp 全部不变,只是把 "集合是否变化"由目录扫描改为写入方免费告知(编译进程内 stub 只增不改)。 二、_create_Vtable_globals 的 O(类数 × 函数数) → O(函数数) 原实现对每个候选类都遍历一遍 self.functions 找 "{ClassName}." 前缀且非 declare 的函数;改为一次性预计算"非 declare 函数名的全部点分前缀"集合, 每类只做一次集合查询。判据等价(startswith(prefix) ⟺ prefix 在点分前缀集)。 重编后请再抓一次 profile 复核收益;下一梯队热点是 _generate_structs (268.6s tottime / 35k 次调用)与 _parse_llvm_type(3.5M 次调用)。 --- lib/Projectrans/Phase2Translator.py | 12 +++++++++++ lib/core/Handles/HandlesImports.py | 31 +++++++++++++++++++++++++++-- lib/core/LLVMCG/StructGen.py | 26 +++++++++++++++--------- 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/lib/Projectrans/Phase2Translator.py b/lib/Projectrans/Phase2Translator.py index f1e0a96..427e870 100644 --- a/lib/Projectrans/Phase2Translator.py +++ b/lib/Projectrans/Phase2Translator.py @@ -1876,6 +1876,11 @@ class Phase2Translator: 不会污染共享缓存。 """ _t0: float = time.time() + # 每个文件翻译入口置脏:本文件/其它文件在此之间新写的 *.stub.ll 全部可见 + # (ImportHandle._build_stub_index 的零 syscall 快路径据此判断是否重扫目录; + # 顺序模式与 worker 模式的每文件粒度皆覆盖,见 MarkStubSetDirty)。 + from lib.core.Handles.HandlesImports import ImportHandle as _IH + _IH.MarkStubSetDirty() with open(src_path, 'r', encoding='utf-8') as f: code = f.read() @@ -2149,6 +2154,9 @@ class Phase2Translator: base = os.path.splitext(out_path)[0] with open(base + '.stub.ll', 'w', encoding='utf-8', newline='\n') as f: f.write(stub_content) + # 新 stub 已落盘 → 置脏,使本文件后续(及下个文件)的索引 miss 能重扫到它 + from lib.core.Handles.HandlesImports import ImportHandle as _IH2 + _IH2.MarkStubSetDirty() with open(base + '.text.ll', 'w', encoding='utf-8', newline='\n') as f: f.write(text_content) self._save_deps(sha1, ModuleSha1Map) @@ -3870,6 +3878,10 @@ class Phase2Translator: # 注册到 stub_files if _CachedIsFile(stub_path): self.stub_files[sha1] = stub_path + # output/.stub.ll 存在(本步刚落盘或从全局缓存拷入)→ 置脏, + # 让后续索引 miss 重扫到新增的 *.stub.ll(见 _build_stub_index 快路径) + from lib.core.Handles.HandlesImports import ImportHandle as _IH3 + _IH3.MarkStubSetDirty() elif _CachedIsFile(sig_path): # 如果 stub 文件不存在,也尝试从 temp 目录查找 temp_stub = os.path.join(self.temp_dir, f"{sha1}.stub.ll") diff --git a/lib/core/Handles/HandlesImports.py b/lib/core/Handles/HandlesImports.py index 8229c4a..2320385 100644 --- a/lib/core/Handles/HandlesImports.py +++ b/lib/core/Handles/HandlesImports.py @@ -161,10 +161,25 @@ class ImportHandle(BaseHandle): _stub_func_cache: dict[str, tuple[str, str, bool, str]] = {} _stub_func_cache_signature: tuple[int, int] | None = None _stub_func_scanned: set[str] = set() + # stub 文件集合自上次建索引以来是否**可能**变化(写 *.stub.ll 的一方显式置脏)。 + # 见 MarkStubSetDirty / _build_stub_index 的零 syscall 快路径:原实现每次 + # _TryLoadStructFromStub 索引 miss 都要 2× os.path.isdir + 2× os.listdir 重新 + # 拼文件集合(profile:_build_stub_index 被调 238k 次;nt._path_isdir 491s + + # nt.listdir 183s ≈ 总时长 30%),而"集合是否变化"完全可以由写入方免费告知。 + _stub_set_dirty: bool = True # 目录 → (listdir 时的目录 mtime_ns, 该次统计出的 *.stub.ll 数量)。 # 键为目录绝对路径:temp/ 与 output/ 分别计缓存。见 _CountStubFilesInDir。 _stub_dir_count_cache: dict[str, tuple[int, int]] = {} + @classmethod + def MarkStubSetDirty(cls) -> None: + """标记「stub 文件集合可能已变化」——**所有写 *.stub.ll 的一方都必须调用**。 + + 调用点多在 Phase2Translator:每个文件翻译入口(跨文件新增一律可见)、 + 写 temp/.stub.ll 之后、注册 include 写 output/.stub.ll 之后。 + """ + ImportHandle._stub_set_dirty = True + def __init__(self, translator: "Translator") -> None: super().__init__(translator) # 实例级去重集合:每个 translator 独立跟踪已加载的 .pyi 和已发射的模块声明。 @@ -2603,7 +2618,16 @@ class ImportHandle(BaseHandle): 增量策略:记录已解析文件集合 _stub_index_scanned,单次编译进程内 stub 文件只增不减(output 逐步填充),只增量解析新增文件; 无新增文件时仅做一次目录集合比较即返回(省去原签名失效后的全量重扫)。 + + 零 syscall 快路径:本函数由 _TryLoadStructFromStub 的**每次索引 miss** + 调用(profile:238k 次),而"stub 集合是否变化"由写入方显式置脏 + (见 MarkStubSetDirty)⇒ 未置脏时直接返回,不再做 + 2× isdir + 2× listdir + 全量 endswith/join(这三项在 profile 里合计 + 约占总时长 30%:nt._path_isdir 491s、nt.listdir 183s、 + np.join/splitroot/endswith ≈ 180s)。 """ + if not ImportHandle._stub_set_dirty: + return ProjectRoot = self._find_project_root() temp_dir = os.path.join(ProjectRoot, 'temp') output_dir = os.path.join(ProjectRoot, 'output') @@ -2619,8 +2643,9 @@ class ImportHandle(BaseHandle): if filename.endswith('.stub.ll'): current_files.add(os.path.join(scan_dir, filename)) - # 无新增文件 → 索引最新,直接返回 + # 无新增文件 → 索引最新,清脏(下次 miss 走零 syscall 快路径) if current_files <= self._stub_index_scanned: + ImportHandle._stub_set_dirty = False return # 只增量解析新增文件(首次调用时全量) @@ -2653,7 +2678,9 @@ class ImportHandle(BaseHandle): if _config_mode == "strict": raise _vlog().warning(f"构建 stub 索引失败: {_e}", "Exception") - self._stub_index_scanned.add(stub_path) + self._stub_index_scanned.add(stub_path) + # 增量解析完成 → 索引与目录一致,清脏(下次 miss 走零 syscall 快路径) + ImportHandle._stub_set_dirty = False @staticmethod def _ExternDeclEmitting(Gen: LlvmGeneratorMixin, class_name: str, source_sha1: str | None) -> bool: diff --git a/lib/core/LLVMCG/StructGen.py b/lib/core/LLVMCG/StructGen.py index beef76a..ee3e01f 100644 --- a/lib/core/LLVMCG/StructGen.py +++ b/lib/core/LLVMCG/StructGen.py @@ -704,6 +704,20 @@ class StructGenMixin: struct_type.set_body(*member_types) def _create_Vtable_globals(self) -> None: + # 「本模块有定义(非 declare)」的函数名所蕴含的全部**点分前缀**集合。 + # 一次 O(函数数) 预计算替代原实现"每个候选类都遍历全部函数"的 + # O(类数 × 函数数)(profile:tottime 75.7s / 1631 次调用 ≈ 46ms per call, + # 因为它对每个跨模块类都要把 self.functions 全扫一遍)。 + # 判据等价:原 `func_name.startswith(f"{ClassName}.") 且非 declare` ⟺ + # `f"{ClassName}."` 出现在某个非 declare 函数名的点分前缀集合里。 + _local_prefixes: set[str] = set() + for _fn, _fo in self.functions.items(): + if getattr(_fo, 'is_declaration', False): + continue + _i: int = _fn.find('.') + while _i != -1: + _local_prefixes.add(_fn[:_i + 1]) + _i = _fn.find('.', _i + 1) for ClassName, methods in self.class_methods.items(): if ClassName in self.Vtables: continue @@ -726,15 +740,9 @@ class StructGenMixin: # 若只存在 declare 而无 define,说明本模块未定义该类,虚表应由定义模块创建。 # vtable linkage='internal',跨模块调用通过对象的 vtable 指针(首字段)完成分派, # 不依赖本模块的 vtable 全局变量。 - has_local_method: bool = False - prefix: str = f"{ClassName}." - for func_name, func_obj in self.functions.items(): - if func_name.startswith(prefix): - # 跳过跨模块的 declare(无函数体),只考虑本模块定义的函数 - if not getattr(func_obj, 'is_declaration', False): - has_local_method = True - break - if not has_local_method: + # 只考虑本模块定义的函数(define,有函数体);跨模块 declare 不算 + # ⇒ _local_prefixes 已按 is_declaration 过滤,此处只查前缀集合。 + if f"{ClassName}." not in _local_prefixes: continue VtableType: ir.ArrayType = ir.ArrayType(ir.PointerType(ir.IntType(8)), len(methods)) Vtable: ir.GlobalVariable = ir.GlobalVariable(self.module, VtableType, name=self._mangle_name(f"{ClassName}_Vtable"))