Permalink
Browse files

Added #time method that tracks timing for block.

  • Loading branch information...
jnunemaker committed Mar 20, 2011
1 parent 80e154f commit 58fe06d6ef82f166fe9aeb3fb17b048c6e57dd0b
Showing with 28 additions and 1 deletion.
  1. +7 −0 lib/statsd.rb
  2. +21 −1 spec/statsd_spec.rb
View
@@ -33,6 +33,13 @@ def count(stat, count, sample_rate=1); send stat, count, 'c', sample_rate end
# @param [Integer] sample_rate sample rate, 1 for always
def timing(stat, ms, sample_rate=1); send stat, ms, 'ms', sample_rate end
+ def time(stat, sample_rate=1)
+ start = Time.now
+ result = yield
+ timing(stat, ((Time.now - start) * 1000).round, sample_rate)
+ result
+ end
+
private
def sampled(sample_rate)
View
@@ -23,7 +23,6 @@ def socket; @socket ||= FakeUDPSocket.new end
end
end
-
describe "#increment" do
it "should format the message according to the statsd spec" do
@statsd.increment('foobar')
@@ -69,6 +68,27 @@ def socket; @socket ||= FakeUDPSocket.new end
end
end
+ describe "#time" do
+ it "should format the message according to the statsd spec" do
+ @statsd.time('foobar') { sleep(0.001); 'test' }
+ @statsd.socket.recv.must_equal ['foobar:1|ms']
+ end
+
+ it "should return the result of the block" do
+ result = @statsd.time('foobar') { sleep(0.001); 'test' }
+ result.must_equal 'test'
+ end
+
+ describe "with a sample rate" do
+ before { class << @statsd; def rand; 0; end; end } # ensure delivery
+
+ it "should format the message according to the statsd spec" do
+ result = @statsd.time('foobar', 0.5) { sleep(0.001); 'test' }
+ @statsd.socket.recv.must_equal ['foobar:1|ms|@0.5']
+ end
+ end
+ end
+
describe "#sampled" do
describe "when the sample rate is 1" do
it "should yield" do

0 comments on commit 58fe06d

Please sign in to comment.