Skip to content

Commit 0976485

Browse files
committed
Make timer a context manager by itself.
1 parent fd12c23 commit 0976485

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

statsd/timer.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,26 @@ def stop(self, subname='total'):
8888
self._stop = time.time()
8989
return self.send(subname, self._stop - self._start)
9090

91+
def __enter__(self):
92+
'''
93+
Make a context manager out of self to measure time execution in a block of code.
94+
95+
:return:
96+
'''
97+
self.start()
98+
return self
99+
100+
def __exit__(self, exc_type, exc_val, exc_tb):
101+
'''
102+
Stop measuring time sending total metric, while exiting block of code.
103+
104+
:param exc_type:
105+
:param exc_val:
106+
:param exc_tb:
107+
:return:
108+
'''
109+
self.stop()
110+
91111
def _decorate(self, name, function, class_=None):
92112
class_ = class_ or Timer
93113

0 commit comments

Comments
 (0)