使用 profile 进行python代码性能分析

定位程序性能瓶颈

对代码优化的前提是需要了解性能瓶颈在什么地方,程序运行的主要时间是消耗在哪里,对于比较复杂的代码可以借助一些工具来定位,python 内置了丰富的性能分析工具,如 profile,cProfile 与 hotshot 等。其中 Profiler 是 python 自带的一组程序,能够描述程序运行时候的性能,并提供各种统计帮助用户定位程序的性能瓶颈。Python 标准模块提供三种 profilers:cProfile,profile 以及 hotshot。

profile 的使用非常简单,只需要在使用之前进行 import 即可。具体实例如下:

 使用 profile 进行性能分析

1 import profile  
2 def profileTest():  
3    Total =1;  
4    for i in range(10):  
5        Total=Total*(i+1)  
6        print Total  
7    return Total  
8 if __name__ == "__main__":  
9    profile.run("profileTest()") 

程序的运行结果如下:

图 1. 性能分析结果

Python 代码性能优化技巧

其中输出每列的具体解释如下:

●ncalls:表示函数调用的次数;

●tottime:表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间;

●percall:(第一个 percall)等于 tottime/ncalls;

●cumtime:表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间;

●percall:(第二个 percall)即函数运行一次的平均时间,等于 cumtime/ncalls;

●filename:lineno(function):每个函数调用的具体信息;

如果需要将输出以日志的形式保存,只需要在调用的时候加入另外一个参数。如 profile.run(“profileTest()”,”testprof”)。

原文地址:https://www.cnblogs.com/whwywzhj/p/6095772.html