python 代码检查,实现行级代码优化

    有时候运行一个python程序,它须要运行很长时间。你或许想提高该程序的运行效率。那该怎么作那?python

     首先须要你要找到该程序瓶颈在哪里~   好比,哪一个函数的运行花费时间比较长? 哪一个函数占用内存比较多,是否须要优化对内存的使用? 哪一个占用cpu时间比较长? 等...   这些都须要考虑,python有几个库能够帮助你解决这些问题~   废话很少说,切入主题。ide


首先写一段读取一个文件的python脚本:函数

touch c9.py

#!/usr/bin/env python
#Date: 2015/07/21

def read_file(fpath):
    BLOCK_SIZE=1024
    with open(fpath, 'rb') as fd:
        block = fd.read(BLOCK_SIZE)
        if block:
            yield block
        else:
            return

def main():
    for i in read_file('~/access.log')
        print i

if __name__ == "__main__":
    main()

 而后,对该代码进行测试。测试


首先测试该代码运行时间:优化

      它是一个外部的python测量。spa

wKiom1Wtq0WjGaA4AAEVu-Nf1Sc199.jpg


real 代表了执行脚本花费的总时间。3d

user 代表了执行脚本花费在cpu的时间。对象

sys 代表了执行脚本花费在内核函数的时间。blog

所以, Real time和user+sys相加的不一样或许代表了时间花费在等待i/o或者是系统在忙于执行其余任务。排序


使用cProfile模块

        若是想知道花费在每一个函数和方法上的时间,以及他们被调用了多少次,你可使用cProfile模块。

$ python -m cProfile -s cumulative  + 要执行的python脚本    ( -s cumulative 它将经过累积花费在每一个函数上的时间来排序)


wKiom1Wtr_7SVO0dAAQLcFGOoa8346.jpg    

你将看到花费在运行你的脚本总时间是比之前高的,这是咱们测量每一个函数执行时间的损失。


使用line_profile模块

        line_profile 给出了在你代码美一行花费cpu时间。

        首先须要安装line_profiler:

                pip install line_profiler


接下来,你须要制定你想使用装饰器@profile评估哪一个函数(你不须要把它import 到你的文件中)   wKiom1WtuhSCJLWTAAIfyDyspWo213.jpg

          

接下来测试该代码:

        $ kernprof -l -v + 要执行的代码

  wKiom1WtunGjlaE-AARCxdynI2o340.jpg

        -l 标识代表了逐行和-v标识代表详细输出。


使用memory_profile模块

        memory_profile模块被用于在逐行的基础上,测量你代码的内存使用率。尽管如此,它可能使得你的代码运行的更慢。

        首先安装memory_profiler

                $pip install memory_profiler

         也建议安装psutil包,使得memory_profile模块运行的更快。

                 $ pip install psutil


相似于line_profile的方式,使用装饰器@profile来标记哪一个函数被跟踪。


$python -m memory_profiler + 要执行的代码文件

wKioL1WtvmGiFjWaAAQImIsWaaQ189.jpg


看上面的输出,注意内存使用率的单位是MiB,这表明的是兆字节(1MiB = 1.05MB).


使用guppy模块

        使用guppy模块你能够跟踪每一个类型在你代码中每一个阶段(字符、元组、字典等等)有多少对象被建立。


安装guppy:

$ pip install guppy


而后将你的代码该改为以下:

#!/usr/bin/env python
from guppy import hpy

def read_file(fpath):
    hp = hpy()
    print "Heap at the beginning of the function\n", hp.heap()
    BLOCK_SIZE = 1024
    with open(fpath, 'rb') as fd:
        while True:
            block = fd.read(BLOCK_SIZE)
            if block:
                yield block
            else:
                print "Heap at the end of the function\n", hp.heap()
                return

def main():
    hp = hpy()
    print "Heap at the beginning of the function\n", hp.heap()
    for i in read_file('/Users/David/Applications/py/dt'):
        #print i
        pass
    print "Heap at the end of the function\n", hp.heap()

if __name__ == "__main__":
    main()


执行该代码:

$ python c9.py


wKioL1WtwlWC7D7qAAgVRIuUZSc843.jpg


经过数据结果,能够看出每一个str、dict、function等对象被建立。


经过以上几个模块,能够更加清晰的了解python代码的执行过程以及对资源的占用状况。对代码优化有很大的帮助~~~ 

相关文章
相关标签/搜索