Python代码性能剖析:cProfile与line_profiler定位瓶颈的秘诀

你的Python代码跑得比蜗牛还慢?今天咱们用两个神器cProfileline_profiler,像侦探查案一样揪出代码里的"拖油瓶"。不需要魔法咒语,只需三分钟就能掌握这两个工具的实战技巧。

自带神器cProfile的基本用法

Python自带的cProfile模块就像代码的X光机。在需要测试的代码前加几行魔法,就能看到每个函数的耗时情况:

import cProfile

def slow_function():
    # 模拟耗时操作
    sum([i**2 for i in range(10000)])

if __name__ == "__main__":
    cProfile.run('slow_function()')

运行后会打印这样的报告:

4 function calls in 0.003 seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.002    0.002    0.002    0.002 :1()
    1    0.000    0.000    0.003    0.003 :1()
    1    0.001    0.001    0.003    0.003 test.py:3(slow_function)
    1    0.000    0.000    0.003    0.003 {built-in method builtins.exec}

关键指标解读&

你可能感兴趣的:(python,开发语言,机器学习)