Python程序如何检测需要优化的代码?

本文介绍了如何通过Python的cProfile和pstats库来定位并优化代码中耗时的部分。首先,通过cProfile分析运行时间,然后使用pstats进行详细统计,按累计时间排序,找出主要消耗时间的函数。通过这种方式,可以科学地进行代码优化,而非凭直觉判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、先分析性能,再进行优化,才能达到性价比最高的优化。

利用下面的2个工具进行分析最占用时间的代码行,然后进行优化

# 不要凭感觉去判断,先获取具体的测评结果
#@ profiler 是纯 python版本,cProfile 是 C 版本(速度更快)

import time
from cProfile import Profile

def test(n=2):
  """测试方法"""
  if n < 0:
    return
  time.sleep(1)
  test(n - 1)


pro = Profile()
pro.runcall(test)

from pstats import Stats # 内置统计

stats = Stats(pro)
stats.strip_dirs()
stats.sort_stats('cumulative')
stats.print_stats() # 打印输出

"""
         8 function calls (5 primitive calls) in 3.002 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      4/1    0.000    0.000    3.002    3.002 <stdin>:1(test)
        3    3.002    1.001    3.002    1.001 {built-in method time.sleep}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

ncalls # 调用次数
tottime # 执行这个函数本身的时间(不包括该函数调用其他函数的时间)
tottime percall # tottime/ncalls ,这个函数的平均时间
cumtime # 执行这个函数花费的总时间(包括该函数调用其他函数的时间)
cumtime percall # cumtime/ncalls ,这个函数的平均总时间
"""

stats.print_callers() # 打印

"""
   Ordered by: cumulative time

Function                                          was called by...
                                                      ncalls  tottime  cumtime
<stdin>:1(test)                                   <-     3/1    0.000    2.001  <stdin>:1(test)
{built-in method time.sleep}                      <-       3    3.002    3.002  <stdin>:1(test)
{method 'disable' of '_lsprof.Profiler' objects}  <- 
Function # 左边是被调用者,后边是调用者

"""

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值