使用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获取网页上图片下载地址的方法
Mar 11 Python
Python之批量创建文件的实例讲解
May 10 Python
Django中create和save方法的不同
Aug 13 Python
python通过SSH登陆linux并操作的实现
Oct 10 Python
如何基于python实现归一化处理
Jan 20 Python
python GUI库图形界面开发之PyQt5复选框控件QCheckBox详细使用方法与实例
Feb 28 Python
对django 2.x版本中models.ForeignKey()外键说明介绍
Mar 30 Python
python按顺序重命名文件并分类转移到各个文件夹中的实现代码
Jul 21 Python
聊聊python中的异常嵌套
Sep 01 Python
详解python内置模块urllib
Sep 09 Python
如何使用python写截屏小工具
Sep 29 Python
Python实战实现爬取天气数据并完成可视化分析详解
Jun 16 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下使用无限生命期Session的方法
2007/03/16 PHP
thinkphp学习笔记之多表查询
2014/07/28 PHP
PHP向浏览器输出内容的4个函数总结
2014/11/17 PHP
thinkPHP+phpexcel实现excel报表输出功能示例
2017/06/06 PHP
Laravel中错误与异常处理的用法示例
2018/09/16 PHP
动态加载js文件 document.createElement
2006/10/14 Javascript
javascript 关闭IE6、IE7
2009/06/01 Javascript
浅谈JavaScript编程语言的编码规范
2011/10/21 Javascript
JavaScript通过this变量快速找出用户选中radio按钮的方法
2015/03/23 Javascript
jquery跟随屏幕滚动效果的实现代码
2016/04/13 Javascript
mac下的nodejs环境安装的步骤
2017/05/24 NodeJs
js提取中文拼音首字母的封装工具类
2018/03/12 Javascript
vue实现员工信息录入功能
2020/06/11 Javascript
利用js canvas实现五子棋游戏
2020/10/11 Javascript
JavaScript构造函数原理及实现流程解析
2020/11/19 Javascript
Python中进程和线程的区别详解
2017/10/29 Python
Python实现文件信息进行合并实例代码
2018/01/17 Python
Python实现按中文排序的方法示例
2018/04/25 Python
深入理解Python中的 __new__ 和 __init__及区别介绍
2018/09/17 Python
Python转换时间的图文方法
2019/07/01 Python
浅析PyTorch中nn.Linear的使用
2019/08/18 Python
python实现超市商品销售管理系统
2019/10/25 Python
django中间键重定向实例方法
2019/11/10 Python
什么是Python中的匿名函数
2020/06/02 Python
如何以Winsows Service方式运行JupyterLab
2020/08/30 Python
详解Pycharm安装及Django安装配置指南
2020/09/15 Python
python中os.remove()用法及注意事项
2021/01/31 Python
HTML5 和小程序实现拍照图片旋转、压缩和上传功能
2018/10/08 HTML / CSS
以色列的身体护理及家居香薰品牌:Sabon NYC
2018/02/23 全球购物
电子专业毕业生自荐信
2014/05/25 职场文书
供用电专业求职信
2014/07/07 职场文书
教师遵守党的政治纪律情况对照检查材料
2014/09/26 职场文书
三严三实对照检查材料思想汇报
2014/09/28 职场文书
2014年党建工作汇报材料
2014/10/27 职场文书
PyTorch dropout设置训练和测试模式的实现
2021/05/27 Python
sass 常用备忘案例详解
2021/09/15 HTML / CSS