Jolly

使用line_profiler分析python代码执行性能
代码的执行性能是程序员需要特别关注的一个点,市面上有很多检测监控python代码执行性能的工具,但是都过于笨重,这...
扫描右侧二维码阅读全文
27
2021/07

使用line_profiler分析python代码执行性能

代码的执行性能是程序员需要特别关注的一个点,市面上有很多检测监控python代码执行性能的工具,但是都过于笨重,这里推荐一个更加轻量,粒度更细的性能测试工具包——line_profiler。

原理与安装

line_profiler作为一个性能测试工具来说是很轻便的,安装也很简单,正常pip安装即可

pip install line_profiler

安装完成后不需要做额外的过多操作,只需要在要测试的方法之上添加一个@profile装饰器。在程序执行时就会自动将测试代码带入测试程序中进行性能测试。

功能测试

这里简单的用一段测试代码测试下,新建test_code文件:

@profile
def test_code():
    a = []

    a.append('1')
    a.append('2')
    a.append('3')
    a.append('4')

    a.extend(['4', '5', '6'])

    c = ''
    for i in a:
        c += i
    print(c)

if __name__ == '__main__':
    test_code()

然后运行测试命令:

kernprof -l -v test_code.py

然后控制台就能看到输出:

1234456
Wrote profile results to test_code.py.lprof
Timer unit: 1e-06 s

Total time: 0.0002404 s
File: test_code.py
Function: test_code at line 3

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           @profile
     4                                           def test_code():
     5         1          2.8      2.8      1.2      a = []
     6
     7         1          2.5      2.5      1.0      a.append('1')
     8         1          1.2      1.2      0.5      a.append('2')
     9         1          1.3      1.3      0.5      a.append('3')
    10         1          1.2      1.2      0.5      a.append('4')
    11
    12         1          2.0      2.0      0.8      a.extend(['4', '5', '6'])
    13
    14         1          0.9      0.9      0.4      c = ''
    15         8          7.0      0.9      2.9      for i in a:
    16         7          8.0      1.1      3.3          c += i
    17         1        213.5    213.5     88.8      print(c)

从输出中可以看到每行代码的耗时以及耗时百分比,可以看到for循环和字符串拼接是比较耗时的,这就是line_profiler的整个使用流程,很简单吧。

Last modification:July 27th, 2021 at 03:21 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment

🌓