First look at a small program, this is the measurement of the time spent in the program, the following is the previous solution example
From Functools import wraps, Partialfrom time import timedef timing (Func=none, Frequencies=1): If Func is None: # Prin T ("+none") return Partial (timing, frequencies=frequencies) # Else: # print ("-none") @wraps (func) def _wrapper ( *args, **kwargs): start_time = time () for T in range (frequencies): result = Func (*args, **kwargs) End_ Times = time () print (' run elapsed: {:. 6f}s. '. Format (end_time-start_time)) return result return _wrapper@timingdef run (): L = [] for I in range (5000000): L.E Xtend ([i]) return Len (L)
Run as follows:
In [4]: Run () Elapsed time: 2.383398s. OUT[4]: 5000000
(like to be inquisitive, you can get rid of comments and think about what kind of output is expected).
Today I inadvertently see the context manager of Python ( Context Manager
), found also very good, in fact, this with
is closely related to the statement, unexpectedly has never cared.
From time import Timedef 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 (' runtime elapsed: {:. 6f}s. '. Format (self.end_time-self.start_time)) with ElapsedTime (): Run2 ()
Summarize
A little bit of official documentation, context management or a lot of content. Python has evolved into the present, but it's not easy. Say simple, but you are not enough to keep pace with the times, master is old-fashioned kick just. Therefore, knowledge needs to be constantly updated to make up for their blind spots, the above is the whole content of this article, I hope we can learn or work to bring some help.