Time method #2

Merged
merged 2 commits into from Apr 18, 2011
View
7 lib/statsd.rb
@@ -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
24 spec/statsd_spec.rb
@@ -1,4 +1,4 @@
-require 'spec/helper'
+require 'helper'
describe Statsd do
before do
@@ -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