使用python装饰器计算函数运行时间的实例

装饰器在python里面有很重要的作用, 如果能够熟练使用,将会大大的提高工作效率

今天就来见识一下 python 装饰器,到底是怎么工作的。

本文主要是利用python装饰器计算函数运行时间

一些需要精确的计算函数运行了多久的程序,都可以采用这种方法  
 

#coding:utf-8 

import urllib2,re,time,random,os,datetime

import HTMLParser

import sys 

reload(sys) 

sys.setdefaultencoding('utf-8') 

  

#计算时间函数 

def print_run_time(func): 

 def wrapper(*args, **kw): 

  local_time = time.time() 

  func(*args, **kw) 

  print 'current Function [%s] run time is %.2f' %
(func.__name__ ,time.time() - local_time) 

 return wrapper 

 

class test:

    def
__init__(self):

       
self.url=''

   
#获取网页页面内容

   
#即装饰器不管参数有多少,都能使用

   
@print_run_time

    def
get_html(self,url):

       
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.2; rv:16.0)
Gecko/20100101 Firefox/16.0'}#设置header

       
req = urllib2.Request(url=url,headers=headers)

       
try:

           
html = urllib2.urlopen(req).read().decode('utf-8')

           
html=HTMLParser.HTMLParser().(html)#处理网页内容, 可以将一些html类型的符号如"
转换回双引号

           
#html =
html.decode('utf-8','replace').encode(sys.getfilesystemencoding())#转码:避免输出出现乱码

except urllib2.HTTPError,e:

           
print(2,u"连接页面失败,错误原因: %s" % e.code)

           
return None

       
except urllib2.URLError,e:

           
if hasattr(e,'reason'):

               
print(2,u"连接页面失败,错误原因:%s" % e.reason)

               
return None

       
return html

       
 

   
#在类的内部使用装饰器

   
@print_run_time

    def
run(self):

       
self.url='http://www.baidu.com'

       
self.get_html(self.url)

       
print 'end'

       
 

#在外面直接使用装饰器

@print_run_time

def get_current_dir(spath):

   
#spath=os.getcwd()

   
#spath=os.path.abspath(os.curdir)

       
 

    for schild
in os.listdir(spath): 

       
schildpath=spath '/' schild 

       
if os.path.isdir(schildpath): 

           
get_current_dir(schildpath) 

       
else: 

           
print schildpath 

   
 

if __name__ == '__main__':

   
my_test=test()

   
my_test.run()

   
spath=os.path.abspath('.')

   
get_current_dir(spath)



运行结果:    

current Function [get_html] run time is
0.29 

end 

current Function [run] run time is 0.29 

05.python_study/03.decorator.py 

current Function [get_current_dir] run time is 0.00



以上这篇使用python装饰器计算函数运行时间的实例就是小编分享给大家的全部内容了

使用python装饰器计算函数运行时间的实例的更多相关文章

  1. python调用时间装饰器检测函数运行时间

    用一个装饰器,监控程序的运行时间 import time def count_time(func): def int_time(*args, **kwargs): start_time = time. ...

  2. 关于Python装饰器内层函数为什么要return目标函数的一些个人见解

    https://blog.csdn.net/try_test_python/article/details/80802199 前几天在学装饰器的时候,关于装饰器内层函数调用目标函数时是否return目 ...

  3. Python 装饰器(Decorators) 超详细分类实例

        Python装饰器分类 Python 装饰器函数: 是指装饰器本身是函数风格的实现; 函数装饰器: 是指被装饰的目标对象是函数;(目标对象); 装饰器类 : 是指装饰器本身是类风格的实现; 类 ...

  4. Python 装饰器 property() 函数

    描述:property() 函数的作用是在新式类中返回属性值. @property 装饰器简单理解就是负责把一个方法变成属性调用 下面理解property()方法语法: class property( ...

  5. Python装饰器基础及运行时间

    一.装饰器基础 装饰器是可调用的对象,其参数是另一个函数(被装饰的函数).装饰器可能会处理被装饰的函数,然后把他返回,或者将其替换成另一个函数或可调用对象. eg:decorate装饰器 @decor ...

  6. Python装饰器(函数)

    闭包 1.作用域L_E_G_B(局部.内嵌.全局...): x=10#全局 def f(): a=5 #嵌套作用域 def inner(): count = 7 #局部变量 print a retur ...

  7. python clock装饰器 计算函数执行时间,执行结果及传入的参数

    import time import functools def clock(func): @functools.wraps(func)#还原被装饰函数的__name__和__doc__属性 def ...

  8. python装饰器三种装饰模式的简单理解

    学设计模式中有个装饰模式,用java实现起来不是很难,但是远远没有python简单,难怪越来越火了! 这里就简单讨论下python的几种装饰模式: 一 无参装饰器: # 装饰器 import time ...

  9. python 装饰器统计某个函数的运行时间

    import datetime def count_time(func): def int_time(*args, **kwargs): start_time = datetime.datetime. ...

随机推荐

  1. 遍历二叉树 - 基于队列的BFS

    之前学过利用递归实现BFS二叉树搜索(http://www.cnblogs.com/webor2006/p/7262773.html),这次学习利用队列(Queue)来实现,关于什么时BFS这里不多说 ...

  2. idea目录因包名而未合并、逐级显示的问题

    如图包名里含有多个.,从而导致一个加载时出现了好多层.. 只要右键java目录,转换为source root就行.

  3. 在MyEclipse10中使用Maven

    虽然很多人说maven比起gradle来已经又落后了,但还是有必要了解一下的. 这两天看了好多文章,也跟着做了很多例子,无一例外,创建的pom.xml文件都是有错的.而且由于使用的开发工具不一致,导致 ...

  4. JS中BOM和DOM之间的关系

    一.Javascript组成JavaScript的实现包括以下3个部分:1.核心(ECMAScript):描述了JS的语法和基本对象.2.文档对象模型 (DOM):处理网页内容的方法和接口.3.浏览器 ...

  5. CSP-S2019 退役记/赛后总结

    真就退役了呗. 作为一名非常失败的OIer,开了一个非常失败的blog,一直想在赛后写点什么,做点什么,总结些什么.自csp结束以来,徘徊了半个月,今夜里终于还是起笔了. 因为从来没写过这种玩意,不妨 ...

  6. org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException

    org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener method ...

  7. Java 注解(Annotations) 详解

    注解是元数据 注解是一种装饰器.一个标记(maker),应用于Java的各种结构之上,例如类.方法.字段.用来为这些结构绑定元数据.注解不包含任何业务逻辑. 只由运行时框架或编译器根据注解信息去执行具 ...

  8. PHP mysqli_real_connect() 函数

    定义和用法mysqli_real_connect() 函数打开一个到 MySQL 服务器的新连接. mysqli_real_connect() 函数与 mysqli_connect() 函数在以下几个 ...

  9. Hibernate 4 升级到 5 后显示未知实体错误

    提示的错误信息如下: org.hibernate.MappingException: Unknown entity: com.ossez.reoc.common.crm.DoNotCall at or ...

  10. 【原创】洛谷 LUOGU P3373 【模板】线段树2

    P3373 [模板]线段树 2 题目描述 如题,已知一个数列,你需要进行下面两种操作: 1.将某区间每一个数加上x 2.将某区间每一个数乘上x 3.求出某区间每一个数的和 输入输出格式 输入格式: 第 ...