Skip to content

Commit

Permalink
Allow starting and stopping timed() manually
Browse files Browse the repository at this point in the history
  • Loading branch information
Tuukka Mustonen committed Aug 31, 2016
1 parent 0c87da3 commit 5f6c120
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
6 changes: 6 additions & 0 deletions datadog/dogstatsd/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,12 @@ def _send(self, start):
elapsed = int(round(1000 * elapsed)) if use_ms else elapsed
self.statsd.timing(self.metric, elapsed, self.tags, self.sample_rate)

def start(self):
self.__enter__()

def stop(self):
self.__exit__(None, None, None)

def timed(self, metric=None, tags=None, sample_rate=1, use_ms=None):
"""
A decorator or context manager that will measure the distribution of a
Expand Down
29 changes: 29 additions & 0 deletions tests/unit/dogstatsd/test_statsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,35 @@ def func(self):
packet = self.recv()
t.assert_equal(packet, None)

def test_timed_start_stop_calls(self):
# In seconds
timer = self.statsd.timed('timed_context.test')
timer.start()
time.sleep(0.5)
timer.stop()

packet = self.recv()
name_value, type_ = packet.split('|')
name, value = name_value.split(':')

t.assert_equal('ms', type_)
t.assert_equal('timed_context.test', name)
self.assert_almost_equal(0.5, float(value), 0.1)

# In milliseconds
timer = self.statsd.timed('timed_context.test', use_ms=True)
timer.start()
time.sleep(0.5)
timer.stop()

packet = self.recv()
name_value, type_ = packet.split('|')
name, value = name_value.split(':')

t.assert_equal('ms', type_)
t.assert_equal('timed_context.test', name)
self.assert_almost_equal(500, float(value), 100)

def test_batched(self):
self.statsd.open_buffer()
self.statsd.gauge('page.views', 123)
Expand Down

0 comments on commit 5f6c120

Please sign in to comment.