有些脚本发现比预期要慢的多,就需要找到瓶颈,然后做相应的优化,参考A guide to analyzing Python performance,也可以说是翻译。

指标

  • 运行时间
  • 时间瓶颈
  • 内存使用
  • 是否有内存泄漏

基本

linux time

这是个shell中自带的命令,也是最简单和方面的方法,但是得到信息太少

[root@bogon util]# time python pvsts.py
Yesterday PV/UV

PV 46300
UV is 3899

real    2m36.591s  #花费时间
user    2m37.167s  #用户态时间
sys     0m2.010s   #内核态时间

如果 sys+user 比 real 小的多,就要考虑io等待时间是否过长了。

使用Cprofile工具

用起来很简单,显示的东西也很多,但是对于代码来说不是很直观

[root@bogon util]# python -m cProfile pvsts.py
Yesterday PV/UV

PV 46300
UV is 3899
         502249600 function calls (502249597 primitive calls) in 250.221 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000  250.221  250.221 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 __future__.py:48(<module>)
        1    0.000    0.000    0.000    0.000 __future__.py:74(_Feature)
        7    0.000    0.000    0.000    0.000 __future__.py:75(__init__)
        1    0.000    0.000    0.000    0.000 __init__.py:49(normalize_encoding)
        1    0.000    0.000    0.000    0.000 __init__.py:71(search_function)
        1    0.000    0.000    0.000    0.000 base64.py:3(<module>)

测试时间工具line_profiler

就是这个小工具,安装很simple

$ pip install line_profiler

在想要测试的函数上添加一个 @profile装饰器(不用倒入任何包,工具会自动倒入)

@profile
def sts_uv():
        #mac_list = []
        mac_set = set()
        with open(temp_log, 'r') as f:
                for line in f.readlines():
                        basid, mac, ip = decode_token(str(line.strip()))
                        #mac_list.append(mac)
                        mac_set.add(mac)
        #uv = len(set(mac_list))
        uv = len(mac_set)
        print "UV is {0}".format(uv)
        return uv

得到结果:

[root@bogon util]# kernprof -l -v pvsts.py
Yesterday PV/UV

PV 46300
UV is 3899
Wrote profile results to pvsts.py.lprof
Timer unit: 1e-06 s

Total time: 450.299 s
File: pvsts.py
Function: sts_uv at line 74

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    74                                           @profile
    75                                           def sts_uv():
    76                                                  #mac_list = []
    77         1           10     10.0      0.0          mac_set = set()
    78         1           59     59.0      0.0         with open(temp_log, 'r') as f:
    79     42431        38556      0.9      0.0                 for line in f.readlines():
    80     42430    450188794  10610.2    100.0                         basid, mac, ip = decode_token(str(line.strip()))
    81                                                                  #mac_list.append(mac)
    82     42430        71491      1.7      0.0                          mac_set.add(mac)
    83                                                  #uv = len(set(mac_list))
    84         1            2      2.0      0.0          uv = len(mac_set)
    85         1           15     15.0      0.0         print "UV is {0}".format(uv)
    86         1            1      1.0      0.0         return uv

同时还是会生成一个pvsts.py.lprof文件

测试内存使用 pip install -U memory_profiler

安装两个工具

$ pip install -U memory_profiler
$ pip install psutil

使用上也是添加一个 ‘@profile’ 装饰器,跟上面的一样。

测试

[root@bogon util]# python -m memory_profiler pvsts.py
Yesterday PV/UV

PV 46300
UV is 3899
Filename: pvsts.py

Line #    Mem usage    Increment   Line Contents
================================================
    74    9.676 MiB    0.000 MiB   @profile
    75                             def sts_uv():
    76                                  #mac_list = []
    77    9.676 MiB    0.000 MiB           mac_set = set()
    78    9.676 MiB    0.000 MiB        with open(temp_log, 'r') as f:
    79   15.289 MiB    5.613 MiB                for line in f.readlines():
    80   15.289 MiB    0.000 MiB                        basid, mac, ip = decode_token(str(line.strip()))
    81                                                  #mac_list.append(mac)
    82   15.289 MiB    0.000 MiB                           mac_set.add(mac)
    83                                  #uv = len(set(mac_list))
    84   14.961 MiB   -0.328 MiB           uv = len(mac_set)
    85   14.961 MiB    0.000 MiB        print "UV is {0}".format(uv)
    86   14.961 MiB    0.000 MiB        return uv

声明:

本文出自 “orangleliu笔记本” 博客,转载请务必保留此出处http://blog.csdn.net/orangleliu/article/details/45934005 作者orangleliu 采用署名-非商业性使用-相同方式共享协议

[Python]程序性能分析的更多相关文章

  1. Python程序性能分析模块----------cProfile

    cProfile分析器可以用来计算程序整个运行时间,还可以单独计算每个函数运行时间,并且告诉你这个函数被调用多少次 def foo(): pass import cProfile cProfile.r ...

  2. python程序性能分析

    中文:http://www.cnblogs.com/zhouej/archive/2012/03/25/2379646.html 英文:https://www.huyng.com/posts/pyth ...

  3. Linux下的应用程序性能分析 总结

    Linux下的应用程序性能分析,根据内核程序和应用程序的不同,下文分两类进行描述. 我们侧重的是应用级别的程序,推荐google perf tool/kcachegrind组合 一.和内核有关的工具 ...

  4. Linux程序性能分析和火焰图

    Linux程序性能分析和火焰图 Linux程序的性能分析工具数量比较多,涉及到整个操作系统的方方面面,可能是开源的原因吧,相对于Windows来说丰富太多.其中应用分析性能方面Dtrace, Syst ...

  5. 八、jdk工具之JvisualVM、JvisualVM之二--Java程序性能分析工具Java VisualVM

    目录 一.jdk工具之jps(JVM Process Status Tools)命令使用 二.jdk命令之javah命令(C Header and Stub File Generator) 三.jdk ...

  6. Golang程序性能分析

    前言 程序性能分析我相信是每个程序员都会遇到的问题,比如说一个程序的CPU为什么占用这么高?有没有优化的空间?又比如程序出现了内存泄漏如何排查等等.如果是C++程序会借助于Google pprof c ...

  7. 一个python 服务器程序性能分析

    该服务器为bono,启动11个进程. 1.设置cprofile 在启动服务的总入口设置cprofile if __name__=="__main__": import cProfi ...

  8. 转帖:Python应用性能分析指南

    原文:A guide to analyzing Python performance While it’s not always the case that every Python program ...

  9. [golang]7种 Go 程序性能分析方法

    视频信息 Seven ways to Profile Go Applicationsby Dave Cheneyat Golang UK Conf. 2016 视频:https://www.youtu ...

随机推荐

  1. ●线段树的三个题(poj 3225,hdu 1542,hdu 1828)

    ●poj 3225 Help with Intervals(线段树区间问题) ○赘述题目 给出以下集合操作: 然后有初始的一个空集S,和以下题目给出的操作指令,并输入指令: 要求进行指令操作后,按格式 ...

  2. hdu 5015(矩阵快速幂z )

    a[i][j] = a[i-1][j] + a[i][j-1] m.特别大,可以计算出第一列,找出规律,构建一个特殊的矩阵,运用快速幂 设矩阵x: 1 0 0 0 ... |10 1 1 1 0 0 ...

  3. hdu 5451(矩阵 +Fibonacci )

    题意:求 [(5 + 2*sqrt(6))^(1 + 2^x)]  % M 基于hdu2256可以求(5 + 2*sqrt(6))^ n 但是n特别大,我们可以找矩阵的循环节 两种可能 1.mod-1 ...

  4. bzoj2338[HNOI2011]数矩形 计算几何

    2338: [HNOI2011]数矩形 Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 1535  Solved: 693[Submit][Status ...

  5. 在QEMU中调试ARM程序【转】

    转自:http://linuxeden.com/html/develop/20100820/104409.html 最近我想调试一个运行在QEMU模拟ARM系统中的Linux程序.我碰到过一些麻烦,因 ...

  6. spring boot新建项目问题总结

    1.启动报:Unregistering JMX-exposed beans on shutdown 原因:以来的Tomcat没有启动 解决办法:在pom.xml加入依赖 <dependency& ...

  7. Linux(CentOs6.3)网络配置

    新装好的虚拟机往往还无法连接网络,本文描述了如何在CentOs6.3系统上配置网络信息 1.windows系统下快捷键windows+r,输入cmd并确定,打开黑窗口 2.黑窗口中输入ipconfig ...

  8. MySQL使用判断

    1.case语法 在第一个方案的返回结果中, value=compare-value.而第二个方案的返回结果是第一种情况的真实结果.如果没有匹配的结果值,则返回结果为ELSE后的结果,如果没有ELSE ...

  9. Java instanceof 关键字是如何实现的?

    作者:RednaxelaFX链接:https://www.zhihu.com/question/21574535/answer/18998914来源:知乎著作权归作者所有.商业转载请联系作者获得授权, ...

  10. B+树在磁盘存储中的应用

    欢迎探讨,如有错误敬请指正 如需转载,请注明出处 http://www.cnblogs.com/nullzx/ 我们首先提一个问题, B+树比平衡二叉树在索引数据方面要快么? 大多数人可能认为肯定还是 ...