Python分析(高级编程三)
调试和性能分析
用 pdb 进行代码调试
1 2 3 4 5 6 7 8 |
import pdb a = 1 b = 2 pdb.set_trace() c = 3 print(a + b + c) |
pdb常用方法
p
(print)打印
n
(next)下一步
s
(step)进入方法内部
l
(list)获取上下文
用 cProfile 进行性能分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import cProfile def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) def fib_seq(n): res = [] if n > 0: res.extend(fib_seq(n-1)) res.append(fib(n)) return res cProfile.run('fib_seq(30)') |
打印参数介绍
- ncalls,是指相应代码 / 函数被调用的次数
- tottime,是指对应代码 / 函数总共执行所需要的时间(注意,并不包括它调用的其他代码 / 函数的执行时间)
- tottime percall,就是上述两者相除的结果,也就是tottime / ncalls
- cumtime,则是指对应代码 / 函数总共执行所需要的时间,这里包括了它调用的其他代码 / 函数的执行时间
- cumtime percall,则是 cumtime 和 ncalls 相除的平均结果。
Leave a Comment