File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -285,6 +285,32 @@ def wrapped(*args, **kwargs):
285285
286286 return InprogressTracker (self )
287287
288+ def time (self ):
289+ '''Time a block of code or function, and set the duration in seconds.
290+
291+ Can be used as a function decorator or context manager.
292+ '''
293+
294+ class Timer (object ):
295+ def __init__ (self , gauge ):
296+ self ._gauge = gauge
297+
298+ def __enter__ (self ):
299+ self ._start = time .time ()
300+
301+ def __exit__ (self , typ , value , traceback ):
302+ # Time can go backwards.
303+ self ._gauge .set (max (time .time () - self ._start , 0 ))
304+
305+ def __call__ (self , f ):
306+ @wraps (f )
307+ def wrapped (* args , ** kwargs ):
308+ with self :
309+ return f (* args , ** kwargs )
310+ return wrapped
311+
312+ return Timer (self )
313+
288314 def set_function (self , f ):
289315 '''Call the provided function to return the Gauge value.
290316
Original file line number Diff line number Diff line change 11from __future__ import unicode_literals
22import os
33import threading
4+ import time
45import unittest
56
67
@@ -108,6 +109,22 @@ def test_gauge_function(self):
108109 x ['a' ] = None
109110 self .assertEqual (1 , self .registry .get_sample_value ('g' ))
110111
112+ def test_function_decorator (self ):
113+ self .assertEqual (0 , self .registry .get_sample_value ('g' ))
114+
115+ @self .gauge .time ()
116+ def f ():
117+ time .sleep (.001 )
118+
119+ f ()
120+ self .assertNotEqual (0 , self .registry .get_sample_value ('g' ))
121+
122+ def test_block_decorator (self ):
123+ self .assertEqual (0 , self .registry .get_sample_value ('g' ))
124+ with self .gauge .time ():
125+ time .sleep (.001 )
126+ self .assertNotEqual (0 , self .registry .get_sample_value ('g' ))
127+
111128
112129class TestSummary (unittest .TestCase ):
113130 def setUp (self ):
You can’t perform that action at this time.
0 commit comments