用python的profile模块找到程序性能瓶颈

昨天学到一招,不用像之前一样想看程序执行慢的时候到底慢在哪里就到处写"start_time = time.time() end_time =  time.time()  use_time = end_time - start_time"了,有一个profile模块可以查看执行过程中各个调用的耗时。

用法是:

import profile

……

profile.run('exe_str')

这里的exe_str代表的就是把我们要执行的代码以字符串形式给profile,如果代码里有单引号要么转义掉,要么字符串外面换用双引号。

比如:

# -*- coding:utf-8 -*-
import profile
import time

def tell_time():
    for i in range(10):
        print time.time()
        
profile.run('tell_time()')

然后除了你代码里输出的东西以外还会有一堆这种东西

         15 function calls in 0.001 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :0(range)
        1    0.001    0.001    0.001    0.001 :0(setprofile)
       10    0.000    0.000    0.000    0.000 :0(time)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        0    0.000             0.000          profile:0(profiler)
        1    0.000    0.000    0.001    0.001 profile:0(tell_time())
        1    0.000    0.000    0.000    0.000 say_hello_profile.py:5(tell_time)

这就是profile返回的程序各个部分的性能情况,很容易找到程序的性能瓶颈。

结果里各项的意义:

 

ncalls函数的被调用次数
tottime函数总计运行时间,除去函数中调用的函数运行时间
percall函数运行一次的平均时间,等于tottime/ncalls
cumtime函数总计运行时间,含调用的函数运行时间
percall函数运行一次的平均时间,等于cumtime/ncalls

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值