Skip to content

Commit

Permalink
Added #time method that tracks timing for block.
Browse files Browse the repository at this point in the history
  • Loading branch information
jnunemaker committed Mar 20, 2011
1 parent 80e154f commit 58fe06d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
7 changes: 7 additions & 0 deletions lib/statsd.rb
Expand Up @@ -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)
Expand Down
22 changes: 21 additions & 1 deletion spec/statsd_spec.rb
Expand Up @@ -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')
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 58fe06d

Please sign in to comment.