使用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 相关文章推荐
Python3实现从文件中读取指定行的方法
May 22 Python
基于ID3决策树算法的实现(Python版)
May 31 Python
Python算法之图的遍历
Nov 16 Python
Python的CGIHTTPServer交互实现详解
Feb 08 Python
python3操作微信itchat实现发送图片
Feb 24 Python
python实现简易通讯录修改版
Mar 13 Python
Python系统监控模块psutil功能与经典用法分析
May 24 Python
用python写扫雷游戏实例代码分享
May 27 Python
python实现抖音点赞功能
Apr 07 Python
django基于存储在前端的token用户认证解析
Aug 06 Python
python自动结束mysql慢查询会话的实例代码
Oct 27 Python
Python LMDB库的使用示例
Feb 14 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
咖啡与水的关系
2021/03/03 冲泡冲煮
用Php编写注册后Email激活验证的实例代码
2013/03/11 PHP
php开启openssl的方法
2014/05/15 PHP
使用PHP处理数据库数据如何将数据返回客户端并显示当前状态
2016/02/16 PHP
JS 如何获取radio选中后的值及不选择取radio的值
2013/10/28 Javascript
浅析jQuery事件之on()方法绑定多个选择器,多个事件
2016/04/27 Javascript
js中class的点击事件没有效果的解决方法
2016/10/13 Javascript
微信小程序 Button 组件详解及简单实例
2017/01/10 Javascript
微信小程序左滑删除效果的实现代码
2017/02/20 Javascript
Javascript封装id、class与元素选择器方法示例
2017/03/13 Javascript
angularjs实现过滤并替换关键字小功能
2017/09/19 Javascript
详解vue的diff算法原理
2018/05/20 Javascript
vue检测对象和数组的变化分析
2018/06/30 Javascript
js jquery 获取某一元素到浏览器顶端的距离实现方法
2018/09/05 jQuery
react 移动端实现列表左滑删除的示例代码
2019/07/04 Javascript
Python实现远程调用MetaSploit的方法
2014/08/22 Python
python 输出上个月的月末日期实例
2018/04/11 Python
解决python3 网络请求路径包含中文的问题
2018/05/10 Python
PyCharm安装第三方库如Requests的图文教程
2018/05/18 Python
详解Django 中是否使用时区的区别
2018/06/14 Python
Pycharm无法显示动态图片的解决方法
2018/10/28 Python
python实现dijkstra最短路由算法
2019/01/17 Python
详解如何管理多个Python版本和虚拟环境
2019/05/10 Python
Python空间数据处理之GDAL读写遥感图像
2019/08/01 Python
Python使用sqlite3模块内置数据库
2020/05/07 Python
Nginx+Uwsgi+Django 项目部署到服务器的思路详解
2020/05/08 Python
html5给汉字加拼音加进度条的实现代码
2020/04/07 HTML / CSS
捷克母婴用品购物网站:Feedo.cz
2020/12/28 全球购物
班长岗位职责
2013/11/10 职场文书
答谢会策划方案
2014/05/12 职场文书
大学感恩节活动总结
2015/05/05 职场文书
春节慰问简报
2015/07/21 职场文书
团支部书记竞选稿
2015/11/21 职场文书
2016年大学光棍节活动总结
2016/04/05 职场文书
2021好看的国漫排行榜前十名 《完美世界》上榜,《元龙》排名第一
2022/03/18 国漫
python+pytest接口自动化之token关联登录的实现
2022/04/06 Python