praekelt/vumi — pull request #667 by hodgestar (2013-12-17 14:31:20+00:00)
Title: Add helper to Timer metric which can be used to time things that overlap in time.

Currently the `Timer` is not useful in situations where runs may overlap (e.g. a `.start()` is called in one event handler and then again in another before the first handler has finished). We need something like:

```diff

diff --git a/vumi/blinkenlights/metrics.py b/vumi/blinkenlights/metrics.py
index 331f43d..c8d818e 100644
--- a/vumi/blinkenlights/metrics.py
+++ b/vumi/blinkenlights/metrics.py
@@ -5,14 +5,15 @@
Includes a publisher, a consumer and a set of simple metrics.
"""

+import time
+import contextlib
+
from twisted.internet.task import LoopingCall
from twisted.python import log

from vumi.service import Publisher, Consumer
from vumi.blinkenlights.message20110818 import MetricMessage

-import time
-

class MetricManager(Publisher):
"""Utility for creating and monitoring a set of metrics.
@@ -276,6 +277,13 @@ class Timer(Metric):
self.stop()
return False

+ @contextlib.contextmanager
+ def timeit(self):
+ start_time = time.time()
+ yield
+ end_time = time.time()
+ self.set(end_time - start_time)
+
def start(self):
if self._start_time is not None:
raise TimerAlreadyStartedError("Attempt to start timer %s that "
```

To make life easier. At the same time we should deprecate the older methods.