示例工程 24-profiling-performance

24-profiling-performance/02-profile-hotspot/profile_hotspot.py

python · 0.9 KB

"""用 cProfile 找出 O(n²) 的热点。"""
 
from __future__ import annotations
 
import cProfile
import io
import pstats
 
 
def find_duplicates(values: list[int]) -> list[int]:
    duplicates: list[int] = []
    for index, value in enumerate(values):
        try:
            values.index(value, 0, index)
        except ValueError:
            continue
        duplicates.append(value)
    return duplicates
 
 
def profile_text(values: list[int]) -> str:
    profiler = cProfile.Profile()
    profiler.enable()
    find_duplicates(values)
    profiler.disable()
    stream = io.StringIO()
    stats = pstats.Stats(profiler, stream=stream)
    stats.sort_stats("tottime").print_stats(5)
    return stream.getvalue()
 
 
def main() -> None:
    values = list(range(2000)) + list(range(500))
    print(profile_text(values))
    print(f"duplicates: {len(find_duplicates(values))}")
 
 
if __name__ == "__main__":
    main()