python性能分析之line_profiler模块-耗时,效率 时间

20210203
直接用pycharm 自带的
在这里插入图片描述

20201215
直接装不上的情况下
先下载安装文件 再安装

line_profiler使用装饰器(@profile)标记需要调试的函数.用kernprof.py脚本运行代码,被选函数每一行花费的cpu时间以及其他信息就会被记录下来。

安装

pip3 install Cpython
pip3 install Cython git+https://github.com/rkern/line_profiler.git

代码演示
loopdemo.py 100以内哪两个数相加等于100.
首先是没有优化过的双层循环的嵌套

@profile
def foo():
    task = []

    for a in range(0, 101):
        for b in range(0, 101):
            if a + b == 100:
                task.append((a, b))
    return task


@profile
def run():
    for item in foo():
        pass


if __name__ == '__main__':
    run()

运行下面的命令

kernprof -l -v loopdemo.py

-l表示逐行分析,-v用于输出。同时会输出一个文件:juliademo.py.lprof,后期可以对.lprof文件进行分析
输出结果

Wrote profile results to loopdemo.py.lprof
Timer unit: 1e-06 s
 
Total time: 0.009856 s
File: loopdemo.py
Function: foo at line 1
 
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           @profile
     2                                           def foo():
     3         1          1.0      1.0      0.0      task = []
     4
     5       102         47.0      0.5      0.5      for a in range(0, 101):
     6     10302       4741.0      0.5     48.1          for b in range(0, 101):
     7     10201       4975.0      0.5     50.5              if a + b == 100:
     8       101         91.0      0.9      0.9                  task.append((a, b))
     9         1          1.0      1.0      0.0      return task
 
Total time: 0.017778 s
File: loopdemo.py
Function: run at line 12
 
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    12                                           @profile
    13                                           def run():
    14       102      17747.0    174.0     99.8      for item in foo():
    15       101         31.0      0.3      0.2          pass

引入kernprof.py会额外的增加是时间,但是为了检测代码每一行发生了什么,这个影响没什么,实际代码运行的时候是不带@profile装饰器的只有需要line_profiler进行逐行分析的时候才需要加。
总用时Total time: 0.017778 s
Hits是调用次数。

%Time 列告诉我们哪行代码占了它所在函数的消耗的时间百分比,可以看出在foo函数中最消耗时间的是判断a+b==100,占用了50.5%的时间。

然后我对循环部分做下面的优化其他地方不变。

    for a in range(0, 101):
        b = 100 - a
        task.append((a, b))
    return task

得到下面的结果

Wrote profile results to loopdemo.py.lprof
Timer unit: 1e-06 s
 
Total time: 0.000126 s
File: loopdemo.py
Function: foo at line 1
 
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           @profile
     2                                           def foo():
     3         1          1.0      1.0      0.8      task = []
     4
     5       102         33.0      0.3     26.2      for a in range(0, 101):
     6       101         47.0      0.5     37.3          b = 100 - a
     7       101         45.0      0.4     35.7          task.append((a, b))
     8         1          0.0      0.0      0.0      return task
 
Total time: 0.000282 s
File: loopdemo.py
Function: run at line 11
 
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    11                                           @profile
    12                                           def run():
    13       102        256.0      2.5     90.8      for item in foo():
    14       101         26.0      0.3      9.2          pass

可以发现总用时,循环体里代码的调用次数减少了

Python是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言,其具有高可扩展性和高可移植性,具有广泛的标准库,受到开发者的追捧,广泛应用于开发运维(DevOps)、数据科学、网站开发和安全。然而,它没有因速度和空间而赢得任何称赞,主要原因是Python是一门动态类型语言,每一个简单的操作都需要大量的指令才能完成。

所以这更加需要开发者在使用Python语言开发项目时协调好程序运行的时间和空间。

1、分析时间耗时
分析项目消耗的时间消耗,依托于line_profiler模块,其可以计算出执行每行代码所需占用的CPU时间。

第1步:安装line_profiler模块,我是用pip安装一直失败,所以下载到本地进行离线安装,指令如下所示:

pip install .\line_profiler-3.0.2-cp37-cp37m-win_amd64.whl
安装成功效果如下所示:

第2步:分析每行代码的运行时间,本案例Demo检测for循环一万次累加和while循环一万次累加的时间,并进行对比,实现代码如下所示:

from line_profiler import LineProfiler
 
def operation1():
  num=0
  for i in range(10000):
    num += 1
 
def operation2():
  num=0
  while(num < 10000):
    num += 1
 
if __name__ == "__main__":
  lprofiler = LineProfiler(operation1,operation2)
  lprofiler.run('operation1()')
  lprofiler.run('operation2()')
  lprofiler.print_stats()

运行程序,可见while循环速度稍微慢一些,效果如下所示:

在这里插入图片描述
2、分析空间耗时
memory_profiler模块可实现对Python项目中每一个代码的内存消耗进行分析和监控。

第1步:安装memory_profiler库文件,指令如下所示:

pip install memory_profiler
安装成功效果如下所示:

第2步:分析每行代码的空间消耗,本案例Demo检测for循环一万次累加和while循环一万次累加的消耗空间,并进行对比,实现代码如下所示:

from memory_profiler import profile
 
@profile
def operation1():
  num=0
  for i in range(10000):
    num += 1
 
@profile
def operation2():
  num=0
  while(num < 10000):
    num += 1
 
if __name__ == "__main__":
  operation1()
  operation2()

由于是简单运算消耗的内存是微乎其微的,效果如下所示:

在这里插入图片描述
https://www.cnblogs.com/2020-zhy-jzoj/p/13164788.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值