秒表作为上下文管理器。
withstopwatch的Python项目详细描述
# pip install withstopwatch# >>> from withstopwatch import StopwatchBasicusage:>>>withStopwatch():...print('<some activity to be measured>')<someactivitytobemeasured>0msUsingfields:>>>withStopwatch()ass:...pass0ms>>>assertisinstance(s.label,str)ands.label=='0 ms'>>>assertisinstance(s.ms,int)ands.ms==0>>>assertisinstance(s.s,int)ands.s==0>>>assertisinstance(s.seconds,float)ands.seconds>0>>>assertisinstance(s.timedelta,datetime.timedelta)>>>assertisinstance(s.start,datetime.datetime)>>>assertisinstance(s.stop,datetime.datetime)`str`and`repr`:>>>assertstr(s)==s.label>>>repr(s)# doctest: +ELLIPSIS'<Stopwatch: datetime.timedelta(0, 0, ...)>'Silenceoptions:>>>withStopwatch(template=None)ass:...pass>>>asserts.labelisNone>>>withStopwatch(file=None)ass:...pass>>>asserts.label=='0 ms'Withdifferenttemplates:>>>withStopwatch(template='passing'):...pass0ms:passing>>>withStopwatch('passing'):...pass0ms:passing>>>withStopwatch('{ms} ms'):...pass0ms>>>withStopwatch('{s} s'):...pass0s>>>withStopwatch('{:.03f} (i.e. {seconds:.03f})'):...pass0.000(i.e.0.000)>>>withStopwatch('{timedelta}'):...pass# doctest: +ELLIPSIS0:00:00.000...>>>withStopwatch('from {start!r} to {stop!r}')ass:...pass# doctest: +ELLIPSISfromdatetime.datetime(...)todatetime.datetime(...)>>>asserts.stop-s.start==s.timedeltaWithanexception(note:duetolimitationsof`doctest`,wecan't checkeasilyboththatsomethingisprintedandthatanexceptionisraised):>>>withStopwatch(file=None):...raiseException()Traceback(mostrecentcalllast):Exception>>>try:...withStopwatch()ass:...raiseException()...exceptExceptionasexc:...print(repr(s))# doctest: +ELLIPSIS0ms(failed)<Stopwatch:datetime.timedelta(0,0,...)>>>>try:...withStopwatch('abc')ass:...raiseException()...exceptExceptionasexc:...print(repr(s))# doctest: +ELLIPSIS0ms:abc(failed)<Stopwatch:datetime.timedelta(0,0,...)>Testingwith`time.sleep`(note:thetestsmayfailduringaslowerrun):>>>importtime>>>withStopwatch()ass:...time.sleep(0.1)100ms>>>assert0.1<s.seconds<0.2Embeddedstopwatchs:>>>withStopwatch('outer'):...withStopwatch('inner'):...pass0ms:inner0ms:outerMeasuringtheoverheadofStopwatchusingStopwatchitself(note:thetestsmayfailduringaslowerrun):>>>withStopwatch(file=None)ass1:...withStopwatch('inner')ass2:...pass0ms:inner>>>withStopwatch(file=None)ass3:...pass>>>overhead=s1.seconds-s3.seconds>>>assert0<=overhead<0.0001...# ~20 us on i5@2.60GHz, Python 3.6.0, Linux