国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

使用python裝飾器計算函數(shù)運行時間的實例

2020-02-22 23:47:29
字體:
供稿:網(wǎng)友

裝飾器在python里面有很重要的作用, 如果能夠熟練使用,將會大大的提高工作效率

今天就來見識一下 python 裝飾器,到底是怎么工作的。

本文主要是利用python裝飾器計算函數(shù)運行時間

一些需要精確的計算函數(shù)運行了多久的程序,都可以采用這種方法

#coding:utf-8 import urllib2,re,time,random,os,datetimeimport HTMLParserimport sys reload(sys) sys.setdefaultencoding('utf-8')  #計算時間函數(shù) 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=''	#獲取網(wǎng)頁頁面內(nèi)容	#即裝飾器不管參數(shù)有多少,都能使用	@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)#處理網(wǎng)頁內(nèi)容, 可以將一些html類型的符號如" 轉(zhuǎn)換回雙引號			#html = html.decode('utf-8','replace').encode(sys.getfilesystemencoding())#轉(zhuǎn)碼:避免輸出出現(xiàn)亂碼		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			#在類的內(nèi)部使用裝飾器	@print_run_time	def run(self):		self.url='http://www.baidu.com'		self.get_html(self.url)		print 'end'		#在外面直接使用裝飾器@print_run_timedef 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)

運行結(jié)果:

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裝飾器計算函數(shù)運行時間的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林站長站。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 晋州市| 瓦房店市| 陆丰市| 抚顺县| 大厂| 巴林左旗| 蒲城县| 孝感市| 上蔡县| 大竹县| 攀枝花市| 夏邑县| 建瓯市| 开鲁县| 和静县| 西充县| 象州县| 承德市| 冷水江市| 溧水县| 宜都市| 阳东县| 阳朔县| 泾阳县| 洛浦县| 西丰县| 民乐县| 莆田市| 潞西市| 阿瓦提县| 密云县| 吕梁市| 微博| 新安县| 定西市| 廊坊市| 北宁市| 定西市| 潮安县| 葫芦岛市| 无棣县|