使用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中比较运算符的使用
May 13 Python
Python类的继承和多态代码详解
Dec 27 Python
python中验证码连通域分割的方法详解
Jun 04 Python
django框架实现模板中获取request 的各种信息示例
Jul 01 Python
Python多叉树的构造及取出节点数据(treelib)的方法
Aug 09 Python
python使用多线程编写tcp客户端程序
Sep 02 Python
win10环境下配置vscode python开发环境的教程详解
Oct 16 Python
python中什么是面向对象
Jun 11 Python
python else语句在循环中的运用详解
Jul 06 Python
Python正则re模块使用步骤及原理解析
Aug 18 Python
Python爬取你好李焕英豆瓣短评生成词云的示例代码
Feb 24 Python
python实现腾讯滑块验证码识别
Apr 27 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/27 PHP
php中强制下载文件的代码(解决了IE下中文文件名乱码问题)
2011/05/09 PHP
PHP之数组学习
2011/05/29 PHP
PHP header()函数使用详细(301、404等错误设置)
2013/04/17 PHP
深入PHP获取随机数字和字母的方法详解
2013/06/06 PHP
laravel自定义分页效果
2017/07/23 PHP
Laravel 修改默认日志文件名称和位置的例子
2019/10/17 PHP
[原创]提供复制本站内容时出现,该文章转自脚本之家等字样的js代码
2007/03/27 Javascript
用JavaScript页面不刷新时全选择,全删除(GridView)
2009/04/14 Javascript
Jquery 1.42 checkbox 全选和反选代码
2010/03/27 Javascript
jquery 如何动态添加、删除class样式方法介绍
2012/11/07 Javascript
JavaScript实现简单的时钟实例代码
2013/11/23 Javascript
jquery的clone方法应用于textarea和select的bug修复
2014/06/26 Javascript
Javascript基础知识(二)事件
2014/09/29 Javascript
JavaScript实现输入框(密码框)出现提示语
2016/01/12 Javascript
所见即所得的富文本编辑器bootstrap-wysiwyg使用方法详解
2016/05/27 Javascript
ng2学习笔记之bootstrap中的component使用教程
2017/03/09 Javascript
基于vue.js实现侧边菜单栏
2017/03/20 Javascript
详解基于node的前端项目编译时内存溢出问题
2017/08/01 Javascript
微信小程序-可移动菜单的实现过程详解
2019/06/24 Javascript
node.js express捕获全局异常的三种方法实例分析
2019/12/27 Javascript
功能完善的小程序日历组件的实现
2020/03/31 Javascript
小程序按钮避免多次调用接口和点击方案实现(不用showLoading)
2020/04/15 Javascript
Python Web框架Flask下网站开发入门实例
2015/02/08 Python
Python 模拟登陆的两种实现方法
2017/08/10 Python
python读取LMDB中图像的方法
2018/07/02 Python
python读取文本中的坐标方法
2018/10/14 Python
kafka-python批量发送数据的实例
2018/12/27 Python
python利用多种方式来统计词频(单词个数)
2019/05/27 Python
对python中的float除法和整除法的实例详解
2019/07/20 Python
大学毕业生的自我鉴定
2013/11/30 职场文书
群众路线剖析材料
2014/09/30 职场文书
苏州园林导游词
2015/02/03 职场文书
南京南京观后感
2015/06/02 职场文书
初三英语教学反思
2016/02/15 职场文书
php 原生分页
2021/04/01 PHP