How to add additional behavior before and after the Python function executes _python

Source: Internet
Author: User

First look at a small program, this is the measurement of the time spent by the program, the following is an example of previous solutions

From Functools import wraps, partial from time
import time

def timing (Func=none, Frequencies=1):
 if Func is No NE:
  # print ("+none") return
  partial (timing, frequencies=frequencies)
 # Else:
  # print ("-none")

 @ Wraps (func)
 def _wrapper (*args, **kwargs):
  start_time = time () to
  T in range (frequencies):
   result = Func (*args, **kwargs)
  end_time = time ()
  print (' Runtime: {:. 6f}s. '. Format (end_time-start_time) return result return

 _wrapper


@timing
def run ():
 l = [] For
 i in range (5000000):
  l.extend ([i]) return
 len (l)

Run as follows:

In [4]: Run ()
time spent: 2.383398s.
Out[4]: 5000000

(like the inquisitive can get rid of annotations and think about what kind of output is expected).

Today accidentally saw the Python context Manager ( Context Manager ), found also very good, in fact, this with is closely related to the statement, unexpectedly has not cared before.

From time import time

def run2 ():
 l = [] for
 I in range (5000000):
  l.extend ([i]) return
 len (l)

Class ElapsedTime ():
 def __enter__ (self):
  Self.start_time = time () return
  self

 def __exit__ (self, Exception_type, Exception_value, traceback):
  self.end_time = time ()
  print (' elapsed hours: {:. 6f}s. '. Format (self.end_time-self.start_time)) with

ElapsedTime ():
 run2 ()

Summarize

A little bit of the official document, the context management is somewhat more content. Python has grown to the present, but it's not easy. Simple, but you do not keep up with the times, master of the old Sanbang just. Therefore, the knowledge needs to renew unceasingly, can make up own blind spot, above is this article entire content, hoped can everybody's study or the work to bring certain help.

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.