安装
pip install line_profiler
如果我从上一遍找到primes这函数最耗时,而想看看里面的代码行耗时,可以在此函数上面添加@profile 符。接着运行
kernprof -l cprofile_test.py
得到一个文件cprofile_test.py.lprof
python -m line_profiler cprofile_test.py.lprof
[root@k8s-node-1 alex]# python -m line_profiler cprofile_test.py.lprof
Timer unit: 1e-06 s
Total time: 88.2254 s
File: cprofile_test.py
Function: primes at line 10
Line # Hits Time Per Hit % Time Line Contents
==============================================================
10 @profile
11 def primes(n):
12
13 40 64.0 1.6 0.0 if n == 2:
14
15 return [2]
16
17 40 34.0 0.8 0.0 elif n < 2:
18
19 return []
20
21 40 21.0 0.5 0.0 s = []
22
23 39999960 18282042.0 0.5 20.7 for i in range(3, n+1):
24
25 39999920 14411959.0 0.4 16.3 if i % 2 != 0:
26
27 19999960 7159780.0 0.4 8.1 s.append(i)
28
29 40 212.0 5.3 0.0 mroot = n ** 0.5
30
31 40 82.0 2.0 0.0 half = (n + 1) / 2 - 1
32
33 40 24.0 0.6 0.0 i = 0
34
35 40 23.0 0.6 0.0 m = 3
36
37 20000 7466.0 0.4 0.0 while m <= mroot:
38
39 19960 7213.0 0.4 0.0 if s[i]:
40
41 6680 2801.0 0.4 0.0 j = (m * m - 3) / 2
42
43 6680 3029.0 0.5 0.0 s[j] = 0
44
45 32449400 10795395.0 0.3 12.2 while j < half:
46
47 32442720 12643545.0 0.4 14.3 s[j] = 0
48
49 32442720 10744559.0 0.3 12.2 j += m
50
51 19960 6664.0 0.3 0.0 i = i + 1
52
53 19960 7618.0 0.4 0.0 m = 2 * i + 3
54
55 40 53.0 1.3 0.0 l = [2]
56
57 20000000 6688249.0 0.3 7.6 for x in s:
58
59 19999960 6286709.0 0.3 7.1 if x:
60
61 3139880 1177810.0 0.4 1.3 l.append(x)
62
63 40 14.0 0.3 0.0 return l
返回结果中 具体 含义:
Total Time:测试代码的总运行时间
Line:代码行号
Hits:表示每行代码运行的次数
Time:每行代码运行的总时间
Per Hits:每行代码运行一次的时间
% Time:每行代码运行时间的百分比
所以直接看 % Time即可
扩展:
https://blog.youkuaiyun.com/guofangxiandaihua/article/details/77825524
https://www.baidu.com/link?url=_XMv8l8RsW_tx4V8zCdBVqUWgKwkYPtoiceaUp2bM9wqYNfFk1lMs5jit3p5WLOwCOu4Yfh6En-BBPsLvIYyPpprOB0MpO4_OWhh7xC_G1y&wd=&eqid=96a058b60000b326000000065af5303d