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.