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


Posted in Python onApril 21, 2018

装饰器在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().unescape(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使用paramiko模块实现ssh远程登陆上传文件并执行
Jan 27 Python
python通过shutil实现快速文件复制的方法
Mar 14 Python
Python自动调用IE打开某个网站的方法
Jun 03 Python
Python实现矩阵加法和乘法的方法分析
Dec 19 Python
pygame游戏之旅 载入小车图片、更新窗口
Nov 20 Python
Python简单处理坐标排序问题示例
Jul 11 Python
django基于restframework的CBV封装详解
Aug 08 Python
python简单实现最大似然估计&scipy库的使用详解
Apr 15 Python
Python实现列表中非负数保留,负数转化为指定的数值方式
Jun 04 Python
Python如何生成xml文件
Jun 04 Python
使用Numpy对特征中的异常值进行替换及条件替换方式
Jun 08 Python
Python几种酷炫的进度条的方式
Apr 11 Python
Python实现针对给定字符串寻找最长非重复子串的方法
Apr 21 #Python
Python 实现一行输入多个值的方法
Apr 21 #Python
Python实现接受任意个数参数的函数方法
Apr 21 #Python
深入分析python数据挖掘 Json结构分析
Apr 21 #Python
Python编程中NotImplementedError的使用方法
Apr 21 #Python
python 通过字符串调用对象属性或方法的实例讲解
Apr 21 #Python
python 限制函数调用次数的实例讲解
Apr 21 #Python
You might like
十天学会php(2)
2006/10/09 PHP
php 前一天或后一天的日期
2008/06/28 PHP
简单PHP上传图片、删除图片实现代码
2010/05/12 PHP
PHP中的MYSQL常用函数(php下操作数据库必备)
2010/09/12 PHP
深入了解 register_globals (附register_globals=off 网站打不开的解决方法)
2012/06/27 PHP
用htc组件制作windows选项卡
2007/01/13 Javascript
jquery ready函数源代码研究
2009/12/06 Javascript
javascript 隐藏/显示指定的区域附HTML元素【legend】用法
2010/03/05 Javascript
不要在cookie中使用特殊字符的原因分析
2010/07/13 Javascript
精通Javascript系列之Javascript基础篇
2011/06/07 Javascript
jQuery ajax 当async为false时解决同步操作失败的问题
2016/11/18 Javascript
React Native实现进度条弹框的示例代码
2017/07/17 Javascript
JavaScript实现AOP详解(面向切面编程,装饰者模式)
2017/12/19 Javascript
React性能优化系列之减少props改变的实现方法
2019/01/17 Javascript
深入浅析Vue 中 ref 的使用
2019/04/29 Javascript
bootstrap中的导航条实例代码详解
2019/05/20 Javascript
vue中组件通信的八种方式(值得收藏!)
2019/08/09 Javascript
Vue2.0 实现页面缓存和不缓存的方式
2019/11/12 Javascript
vue实现全屏滚动效果(非fullpage.js)
2020/03/07 Javascript
Python数据类型详解(四)字典:dict
2016/05/12 Python
Python实现朴素贝叶斯的学习与分类过程解析
2019/08/24 Python
pip install 使用国内镜像的方法示例
2020/04/03 Python
html5理解head_动力节点Java学院整理
2017/07/13 HTML / CSS
有影响力的品牌之家:Our Social Collective
2019/06/08 全球购物
How TDD works
2012/09/30 面试题
家具厂厂长岗位职责
2014/01/01 职场文书
黄继光的英雄事迹材料
2014/02/13 职场文书
网络工程师自荐书范文
2014/04/01 职场文书
小学生志愿者活动方案
2014/08/23 职场文书
有限责任公司股东合作协议书
2014/12/02 职场文书
三八妇女节寄语
2015/02/27 职场文书
2015年求职自荐信范文
2015/03/04 职场文书
爱心捐助活动总结
2015/05/09 职场文书
新店开张宣传语
2015/07/13 职场文书
2019年描写人生经典诗句大全
2019/07/08 职场文书
使用pandas或numpy处理数据中的空值(np.isnan()/pd.isnull())
2021/05/14 Python