使用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实现3行代码解简单的一元一次方程
Aug 18 Python
python获取一组数据里最大值max函数用法实例
May 26 Python
fastcgi文件读取漏洞之python扫描脚本
Apr 23 Python
python、java等哪一门编程语言适合人工智能?
Nov 13 Python
Python虚拟环境项目实例
Nov 20 Python
Python Pandas批量读取csv文件到dataframe的方法
Oct 08 Python
解决Pycharm界面的子窗口不见了的问题
Jan 17 Python
Python零基础入门学习之输入与输出
Apr 03 Python
python图形绘制奥运五环实例讲解
Sep 14 Python
python读取tif图片时保留其16bit的编码格式实例
Jan 13 Python
使用 Python 读取电子表格中的数据实例详解
Apr 17 Python
pytorch model.cuda()花费时间很长的解决
Jun 01 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使用$_POST或$_SESSION[]向js函数传参
2014/09/16 PHP
PHP+MySQL修改记录的方法
2015/01/21 PHP
PHP水印类,支持添加图片、文字、填充颜色区域的实现
2017/02/04 PHP
Jquery选择器 $实现原理
2009/12/02 Javascript
基于BootStarp的Dailog
2016/04/28 Javascript
预防网页挂马的方法总结
2016/11/03 Javascript
JS控制TreeView的结点选择
2016/11/11 Javascript
微信小程序模板之分页滑动栏
2017/02/10 Javascript
Linux CentOS系统下安装node.js与express的方法
2017/04/01 Javascript
vue如何引用其他组件(css和js)
2017/04/13 Javascript
JavaScript中var、let、const区别浅析
2018/06/24 Javascript
Vue SPA单页应用首屏优化实践
2018/06/28 Javascript
Vue+Webpack完美整合富文本编辑器TinyMce的方法
2018/11/30 Javascript
[03:56]还原FTP电影首映式 DOTA2群星拼出遗迹世界
2014/03/26 DOTA
Python中无限元素列表的实现方法
2014/08/18 Python
Python multiprocessing.Manager介绍和实例(进程间共享数据)
2014/11/21 Python
Python __setattr__、 __getattr__、 __delattr__、__call__用法示例
2015/03/06 Python
Python实现快速排序和插入排序算法及自定义排序的示例
2016/02/16 Python
独特的python循环语句
2016/11/20 Python
Python 异常处理的实例详解
2017/09/11 Python
利用python解决mysql视图导入导出依赖的问题
2017/12/17 Python
使用Python获取网段IP个数以及地址清单的方法
2018/11/01 Python
python判断一个数是否能被另一个整数整除的实例
2018/12/12 Python
Python新手学习标准库模块命名
2020/05/29 Python
Python操作word文档插入图片和表格的实例演示
2020/10/25 Python
Python 使用office365邮箱的示例
2020/10/29 Python
python 三种方法实现对Excel表格的读写
2020/11/19 Python
日本最大的购物网站乐天市场国际版:Rakuten Global Market(支持中文)
2020/02/03 全球购物
代理商会议邀请函
2014/01/27 职场文书
家居饰品店创业计划书
2014/01/31 职场文书
小学教师师德感言
2014/02/10 职场文书
职员竞岗演讲稿
2014/05/14 职场文书
优秀乡村医生事迹材料
2014/05/28 职场文书
飞机制造技术专业求职信
2014/07/27 职场文书
Python 中的单分派泛函数你真的了解吗
2021/06/22 Python
MySQL count(*)统计总数问题汇总
2022/09/23 MySQL