日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python计算时间装饰器_使用python装饰器计算函数运行时间的实例

發布時間:2025/3/15 python 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python计算时间装饰器_使用python装饰器计算函数运行时间的实例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

裝飾器在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().(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):

總結

以上是生活随笔為你收集整理的python计算时间装饰器_使用python装饰器计算函数运行时间的实例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。