摘要:本篇博客简单讲解如何给Python程序做profile。profie很有用的,它可以分解程序各个部分花费了多少时间。
1 line_profiler
在linux下我用time这个命令可以查看程序运行的总时间,user mode时间和kernel mode时间。但是如果想更进一步,查看程序内部哪一行命令花费多少时间,或者查找程序的瓶颈部分,就得用 line_profiler 这个包了。这对于优化程序很有帮助。
1.1 安装
官方安装方法:
pip install line_profiler
但是我用这个方法安装失败了。。。我是Anaconda环境,于是使用conda安装,成功了:
conda install line_profiler
2 使用
分为三个步骤:
- import line_profiler
- 给函数加上 @profile 这个装饰器
- 在命令行里面输入 kernprof -v -l code.py
这里code.py 是要做profile的程序
3 Talk is cheap, show me the code.
代码:
import line_profiler
// ...
@profile
def findSubstring(self, s: str, words: List[str]) -> List[int]:
''' s -- O(N)
words -- O(M)
'''
from collections import defaultdict
if