python如何分析程序性能

when use Profiler?
有时候你觉得程序运行很慢,想对程序进行优化,但是你又不知道哪部分程序入手,这时候你就需要对程序整体性能进行分析,看看速度慢主要是哪部分程序导致的

why use cProfile?
cProfile,一个python程序性能分析模块。其实Python有两个profiler,Profile和cProfile,前者是纯Python写的,会产生比较大的开销,测试结果不准确。后者是c语言扩展模块,对受测程序影响比较小,所以推荐用cProfile.

how to use cProfile?
首先有以下程序:

from cProfile import Profile 
from pstats import Stats

def for1():
    y = 0
    for i in range(100):
        y = y +i

def for2():
    y = 0
    for i in range(1000000):
        y = y + i

def test():     
    for1()
    for2()

现在要对test进行分析:

if __name__ == "__main__":
    profiler = Profile() #创建profiler对象
    profiler.runcall(test) #对test进行测试
    stats = Stats(profiler)
    stats.strip_dirs()
    stats.sort_stats('cumulative')
    stats.print_stats()

结果如下:

  4 function calls in 0.192 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.192    0.192 main.py:48(test1)
        1    0.192    0.192    0.192    0.192 main.py:43(for2)
        1    0.000    0.000    0.000    0.000 main.py:38(for1)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

要分析该结果,我们先要知道几个名词的意思(从左到右)
ncalls:函数在性能分析期间调用的次数
tottime:函数总的运行时间,除去子函数的运行时间
percall:tottime/ncalls
cumtime:该函数包括子函数的累计时间
percall:cumtime/ncalls
filename:lineno(function):函数调用的信息

ok,到这里,你就可以看出来for2函数运行时间是最长的了,因为它cumtime比for1的大。

我们还使用了pstats的Stats类:
stats = Stats(profiler):创建对象
stats.strip_dirs():去掉无关路径信息
stats.sort_stats(‘cumulative’):按累计时间进行排序,也可以按照calls, cumulative,line, module, name, nfl, pcalls, stdname, time进行排序
stats.print_stats():打印统计消息,如果想打印top2的信息,则 stats.print_stats(2)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值