使用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装饰器计算函数运行时间的实例的更多相关文章
- python调用时间装饰器检测函数运行时间
用一个装饰器,监控程序的运行时间 import time def count_time(func): def int_time(*args, **kwargs): start_time = time. ...
- 关于Python装饰器内层函数为什么要return目标函数的一些个人见解
https://blog.csdn.net/try_test_python/article/details/80802199 前几天在学装饰器的时候,关于装饰器内层函数调用目标函数时是否return目 ...
- Python 装饰器(Decorators) 超详细分类实例
Python装饰器分类 Python 装饰器函数: 是指装饰器本身是函数风格的实现; 函数装饰器: 是指被装饰的目标对象是函数;(目标对象); 装饰器类 : 是指装饰器本身是类风格的实现; 类 ...
- Python 装饰器 property() 函数
描述:property() 函数的作用是在新式类中返回属性值. @property 装饰器简单理解就是负责把一个方法变成属性调用 下面理解property()方法语法: class property( ...
- Python装饰器基础及运行时间
一.装饰器基础 装饰器是可调用的对象,其参数是另一个函数(被装饰的函数).装饰器可能会处理被装饰的函数,然后把他返回,或者将其替换成另一个函数或可调用对象. eg:decorate装饰器 @decor ...
- Python装饰器(函数)
闭包 1.作用域L_E_G_B(局部.内嵌.全局...): x=10#全局 def f(): a=5 #嵌套作用域 def inner(): count = 7 #局部变量 print a retur ...
- python clock装饰器 计算函数执行时间,执行结果及传入的参数
import time import functools def clock(func): @functools.wraps(func)#还原被装饰函数的__name__和__doc__属性 def ...
- python装饰器三种装饰模式的简单理解
学设计模式中有个装饰模式,用java实现起来不是很难,但是远远没有python简单,难怪越来越火了! 这里就简单讨论下python的几种装饰模式: 一 无参装饰器: # 装饰器 import time ...
- python 装饰器统计某个函数的运行时间
import datetime def count_time(func): def int_time(*args, **kwargs): start_time = datetime.datetime. ...
随机推荐
- vscode 右键打开
Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\shell\VSCode] @="Open with Code" ...
- 牛客第十场 F.Popping Balloons
第一维直接遍历 第二维用线段树维护每个最左端可以得到的贡献 在线段树上每次删除一个点会影响到 X X-R X-2*R 3个值 最多操作1e5次 复杂度 6*n*logn(删了还要加回来 #i ...
- appium连接Android真机,并调试
Android真机:华为pad2 Android和Windows连接同一个局域网 连接USB Android机设置: 打开USB调试 cmd>adb devices,显示Android序列号 , ...
- python_lambda表达式(匿名函数)
# lambda表达式,为了解决简单函数的情况,如: def func(a1,a2): return a1 + a2 func = lambda a1,a2:a1+a2 # 上面这两个是一样的 def ...
- Aizu - 1383 Pizza Delivery (最短路图+DAG上的割边)
题意:给出一张有向图,每条边有长度,对于每条边,你要回答将该边的方向取反后,从起点到终点的最短距离是增加or减小or不变. 首先求出起点到所有点的最短距离和所有点到终点的最短距离(两次DIjkstra ...
- 前端小白页面开发注意事项及小工具(html\css\js)
技术一直在向前发展.但是有一些是相通的,要找准重点,将80%的时间放在提升基础问题上,余下的20%再去学习框架,库和工具. HTML 1. HTML 属性应当按照以下给出的顺序依次排列,确保代码的易读 ...
- vue初级尝试
为了跟上前端后台化的潮流,本少不得不开始关注vue,下列上机代码是针对App.vue进行的更改 数据渲染----一般键值对,数组,对象和对象数组 <template> <div id ...
- BZOJ 4522: [Cqoi2016]密钥破解 (Pollard-Rho板题)
Pollard-Rho 模板 板题-没啥说的- 求逆元出来后如果是负的记得加回正数 CODE #include<bits/stdc++.h> using namespace std; ty ...
- CI环境搭建-创建git
添加如下配置: 上图说的需每次启动的即下面这个文件: 默认用户名.密码是admin/admin 创建代码仓库: 选择版本库: 使用方法: 1,创建一个文件夹 选择版本库地址: 也可以通过c ...
- js 获取当前focus 的 input 元素
document.querySelector("#pro-code").focus(); console.log("focus:" + document.act ...