示例工程 40-type-checker-in-python

40-type-checker-in-python/06-perf-large-file/perf_large_file.py

python · 1.4 KB

"""1 万行源码的 AST 遍历耗时。"""
 
from __future__ import annotations
 
import ast
import time
 
 
def generate(lines: int) -> str:
    return "".join(f"v{index} = {index}\n" for index in range(lines))
 
 
def check(source: str) -> list[str]:
    tree = ast.parse(source)
    env: dict[str, str] = {}
    errors: list[str] = []
    for node in tree.body:
        if not isinstance(node, ast.Assign) or not isinstance(node.value, ast.Constant):
            continue
        value = node.value.value
        kind = "int" if isinstance(value, int) else "str" if isinstance(value, str) else "unknown"
        for target in node.targets:
            if isinstance(target, ast.Name):
                if target.id in env and env[target.id] != kind:
                    errors.append("E003")
                env[target.id] = kind
    return errors
 
 
def count_nodes(source: str) -> int:
    return sum(1 for _ in ast.walk(ast.parse(source)))
 
 
def best_ms(source: str, repeats: int = 3) -> float:
    timings: list[float] = []
    for _ in range(repeats):
        start = time.perf_counter()
        check(source)
        timings.append((time.perf_counter() - start) * 1000)
    return min(timings)
 
 
def main() -> None:
    source = generate(10_000)
    print(f"lines: {source.count(chr(10))}")
    print(f"nodes: {count_nodes(source)}")
    print(f"errors: {check(source)}")
    print(f"best_ms: {best_ms(source):.1f}")
 
 
if __name__ == "__main__":
    main()