Skip to content

Loading…

Time method #2

Merged
merged 2 commits into from

2 participants

@jnunemaker

Added a time method that handles tracking the timing of a block.

@reinh reinh merged commit 58fe06d into reinh:master
@reinh
Owner

Merged (finally). Thanks!

@j-manu j-manu referenced this pull request in j-manu/statsd-ruby
@j-manu j-manu Ignore socket errors even if logger is not set.
Closes #2
fecfbc5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Showing with 29 additions and 2 deletions.
  1. +7 −0 lib/statsd.rb
  2. +22 −2 spec/statsd_spec.rb
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
Something went wrong with that request. Please try again.