使用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模块学习 filecmp 文件比较
Aug 27 Python
python处理cookie详解
Feb 07 Python
python实现从ftp服务器下载文件的方法
Apr 30 Python
Python内存管理方式和垃圾回收算法解析
Nov 11 Python
TensorFlow搭建神经网络最佳实践
Mar 09 Python
在python里面运用多继承方法详解
Jul 01 Python
用Python实现BP神经网络(附代码)
Jul 10 Python
Python Django Vue 项目创建过程详解
Jul 29 Python
Python 实现训练集、测试集随机划分
Jan 08 Python
python小程序之4名牌手洗牌发牌问题解析
May 15 Python
Python API 操作Hadoop hdfs详解
Jun 06 Python
pandas中DataFrame数据合并连接(merge、join、concat)
May 30 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中使用crypt()实现用户身份验证的代码
2012/09/05 PHP
php中的四舍五入函数代码(floor函数、ceil函数、round与intval)
2014/07/14 PHP
destoon文章模块调用企业会员资料的方法
2014/08/22 PHP
setTimeout和setInterval的区别你真的了解吗?
2011/03/31 Javascript
滚动图片效果 jquery实现回旋滚动效果
2013/01/08 Javascript
(跨浏览器基础事件/浏览器检测/判断浏览器)经验代码分享
2013/01/24 Javascript
jQuery中get和post方法传值测试及注意事项
2014/08/08 Javascript
JQuery 实现在同一页面锚点链接之间的平滑滚动
2014/10/29 Javascript
javascript实现input file上传图片预览效果
2015/12/31 Javascript
解析预加载显示图片艺术
2016/12/05 Javascript
jQuery插件FusionCharts实现的3D帕累托图效果示例【附demo源码】
2017/03/25 jQuery
微信小程序 选项卡的简单实例
2017/05/24 Javascript
js实现城市级联菜单的2种方法
2017/06/23 Javascript
基于vue-router 多级路由redirect 重定向的问题
2018/09/03 Javascript
Vue.js路由实现选项卡简单实例
2019/07/24 Javascript
世界上最短的数字判断js代码
2019/09/09 Javascript
python 遍历字符串(含汉字)实例详解
2017/04/04 Python
Python 编码规范(Google Python Style Guide)
2018/05/05 Python
查看Django和flask版本的方法
2018/05/14 Python
python使用epoll实现服务端的方法
2018/10/16 Python
Python+OpenCV实现图像融合的原理及代码
2018/12/03 Python
python把转列表为集合的方法
2019/06/28 Python
简单了解django orm中介模型
2019/07/30 Python
Python re 模块findall() 函数返回值展现方式解析
2019/08/09 Python
在Anaconda3下使用清华镜像源安装TensorFlow(CPU版)
2020/04/19 Python
Python发送邮件封装实现过程详解
2020/05/09 Python
Python 使用双重循环打印图形菱形操作
2020/08/09 Python
贪睡宠物用品:Snoozer Pet Products
2020/02/04 全球购物
关心下一代工作先进事迹
2014/08/15 职场文书
2014年教师节讲话稿5篇
2014/09/10 职场文书
购房委托书
2014/10/15 职场文书
业务员岗位职责范本
2015/04/03 职场文书
公司客户答谢酒会祝酒词
2015/08/11 职场文书
2015秋季田径运动会广播稿
2015/08/19 职场文书
Spring Boot mybatis-config 和 log4j 输出sql 日志的方式
2021/07/26 Java/Android
一级电子管军用接收机测评
2022/04/05 无线电