Calculate function run time using Python adorner

Source: Internet
Author: User
Tags python decorator
Below for you to share an example of using the Python adorner to calculate the running time of the function, with a good reference value, I hope to help you. Come and see it together.

Adorners have a very important role in Python, if they can be used skillfully, will greatly improve the efficiency

Let's see how the Python decorator works today.

This article mainly uses the Python decorator to calculate the function running time

Some programs that require a precise calculation of how long the function runs can be used in this way

#coding: utf-8 import urllib2,re,time,random,os,datetimeimport htmlparserimport 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 WR Apper class Test:def __init__ (self): self.url= ' #获取网页页面内容 # that is, the adorner can use @print_run_timedef get_html (Self,url) regardless of the number of parameters: headers = {' user-agent ': ' mozilla/5.0 (Windows NT 6.2; rv:16.0) gecko/20100101 firefox/16.0 '} #设置headerreq = Urllib2. Request (url=url,headers=headers) try:html = Urllib2.urlopen (req). Read (). Decode (' Utf-8 ') html=htmlparser.htmlparser (). unescape (HTML) #处理网页内容, you can convert some HTML type symbols such as "back to double quotes #html = Html.decode (' utf-8 ', ' replace '). Encode ( Sys.getfilesystemencoding ()) #转码: Avoid garbled except URLLIB2 output. Httperror,e:print (2,u "Connection page failed with error reason:%s"% E.code) return noneexcept urllib2. Urlerror,e:if hasattr (E, ' reason '):p rint (2,u "Connection page failed with error reason:%s"% E.reason) return Nonereturn html# inside the classUsing the adorner @print_run_timedef run (self): self.url= ' http://www.baidu.com ' self.get_html (self.url) print ' End ' # Use the adorner directly outside @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)

Operation Result:

Current function [get_html] run time was 0.29 end current function [run] run time is 0.29 05.python_study/03.decorator.py C Urrent Function [Get_current_dir] Run time is 0.00

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.