优化Python首先需要通过分析来找到真正的瓶颈 — 永远不要猜测。Python是解释型、动态类型的语言,这使得它比编译型语言慢,所以优化的重点是改进算法、利用C支撑的库,以及减少热路径中的解释器开销。
先进行分析
python
import cProfile
cProfile.run("my_function()") # shows time spent per function call
# line-level profiling (third-party)
# pip install line_profiler → @profile decorator → kernprof -l -v script.py
bash
python -m cProfile -s cumtime script.py
