python 内置了丰富的性能分析工具,如 profile,cProfile 与 hotshot 等。其中 Profiler 是 python 自带的一组程序,能够描述程序运行时候的性能,并提供各种统计帮助用户定位程序的性能瓶颈。Python 标准模块提供三种 profilers:cProfile,profile 以及 hotshot。

import profile
import pstats

def profileTest():
    Total = 1;
    for i in range(10):
        Total = Total * (i + 1)
        print( Total)
    return Total


if __name__ == "__main__":
    profile.run("profileTest()","testprof")#删除第二个参数,则不以日志形式导出,此时性能分析的结果会显示出来
    p = pstats.Stats('testprof')
    p.sort_stats("name").print_stats()

对于大型应用程序,如果能够将性能分析的结果以图形的方式呈现,将会非常实用和直观,常见的可视化工具有 Gprof2Dot,visualpytune,KCacheGrind 等

将关键 python 代码部分重写成 C 扩展模块,或者选用在性能上更为优化的解释器等,这些在本文中统称为优化工具。python 有很多自带的优化工具,如 Psyco,Pypy,Cython,Pyrex 等