File tree 2 files changed +43
-0
lines changed 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -285,6 +285,32 @@ def wrapped(*args, **kwargs):
285
285
286
286
return InprogressTracker (self )
287
287
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
+
288
314
def set_function (self , f ):
289
315
'''Call the provided function to return the Gauge value.
290
316
Original file line number Diff line number Diff line change 1
1
from __future__ import unicode_literals
2
2
import os
3
3
import threading
4
+ import time
4
5
import unittest
5
6
6
7
@@ -108,6 +109,22 @@ def test_gauge_function(self):
108
109
x ['a' ] = None
109
110
self .assertEqual (1 , self .registry .get_sample_value ('g' ))
110
111
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
+
111
128
112
129
class TestSummary (unittest .TestCase ):
113
130
def setUp (self ):
You can’t perform that action at this time.
0 commit comments