使用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中表达式x += y和x = x+y 的区别详解
Jun 20 Python
Python实现求数列和的方法示例
Jan 12 Python
python 读取dicom文件,生成info.txt和raw文件的方法
Jan 24 Python
Python基础学习之时间转换函数用法详解
Jun 18 Python
Python分析彩票记录并预测中奖号码过程详解
Jul 09 Python
python 模拟贷款卡号生成规则过程解析
Aug 30 Python
python 实现快速生成连续、随机字母列表
Nov 28 Python
详解Python 重学requests发起请求的基本方式
Feb 07 Python
pytorch masked_fill报错的解决
Feb 18 Python
利用Python实现Excel的文件间的数据匹配功能
Jun 16 Python
详解matplotlib中pyplot和面向对象两种绘图模式之间的关系
Jan 22 Python
Python虚拟环境virtualenv是如何使用的
Jun 20 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下一个非常全面获取图象信息的函数
2008/11/20 PHP
给ECShop添加最新评论
2015/01/07 PHP
PHP使用FFmpeg获取视频播放总时长与码率等信息
2016/09/13 PHP
php使用PDO从数据库表中读取数据的实现方法(必看)
2017/06/02 PHP
prototype Element学习笔记(Element篇三)
2008/10/26 Javascript
js和as的稳定传值问题解决
2013/07/14 Javascript
javascript计时器事件使用详解
2014/01/07 Javascript
使用focus方法让光标默认停留在INPUT框
2014/07/29 Javascript
利用jQuery及AJAX技术定时更新GridView的某一列数据
2015/12/04 Javascript
JS组件Bootstrap Select2使用方法详解
2020/04/17 Javascript
jquery 将当前时间转换成yyyymmdd格式的实现方法
2016/06/01 Javascript
jQuery Ajax 异步加载显示等待效果代码分享
2016/08/01 Javascript
BootStrap 动态添加验证项和取消验证项的实现方法
2016/09/28 Javascript
完美解决node.js中使用https请求报CERT_UNTRUSTED的问题
2017/01/08 Javascript
通过命令行生成vue项目框架的方法
2017/07/12 Javascript
基于js原生和ajax的get和post方法以及jsonp的原生写法实例
2017/10/16 Javascript
jquery动态添加以及遍历option并获取特定样式名称的option方法
2018/01/29 jQuery
详解React服务端渲染从入门到精通
2019/03/28 Javascript
vue路由守卫及路由守卫无限循环问题详析
2019/09/05 Javascript
vue数据更新UI不刷新显示的解决办法
2020/08/06 Javascript
Ant design vue table 单击行选中 勾选checkbox教程
2020/10/24 Javascript
Python内置数据类型详解
2014/08/18 Python
python操作mysql中文显示乱码的解决方法
2014/10/11 Python
Python实现Linux的find命令实例分享
2017/06/04 Python
简单了解什么是神经网络
2017/12/23 Python
Python3中的json模块使用详解
2018/05/05 Python
利用Python小工具实现3秒钟将视频转换为音频
2019/10/29 Python
Python如何使用argparse模块处理命令行参数
2019/12/11 Python
python 实现简单的FTP程序
2019/12/27 Python
幼儿园教育教学反思
2014/01/31 职场文书
小班上学期个人总结
2015/02/12 职场文书
2015年12.4全国法制宣传日活动总结
2015/03/24 职场文书
建筑工地资料员岗位职责
2015/04/13 职场文书
2016年“11.11”光棍节活动总结
2016/04/05 职场文书
Python 循环读取数据内存不足的解决方案
2021/05/25 Python
Java如何实现树的同构?
2021/06/22 Java/Android