Skip to content
This repository

Time method #2

Merged
merged 2 commits into from about 3 years ago

2 participants

John Nunemaker Rein Henrichs
John Nunemaker

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

Rein Henrichs reinh merged commit 58fe06d into from April 18, 2011
Rein Henrichs reinh closed this April 18, 2011
Rein Henrichs
Owner
reinh commented April 18, 2011

Merged (finally). Thanks!

Manu J j-manu referenced this pull request from a commit in j-manu/statsd-ruby May 30, 2012
Manu J 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
This page is out of date. Refresh to see the latest.
7  lib/statsd.rb
@@ -33,6 +33,13 @@ def count(stat, count, sample_rate=1); send stat, count, 'c', sample_rate end
33 33
   # @param [Integer] sample_rate sample rate, 1 for always
34 34
   def timing(stat, ms, sample_rate=1); send stat, ms, 'ms', sample_rate end
35 35
 
  36
+  def time(stat, sample_rate=1)
  37
+    start = Time.now
  38
+    result = yield
  39
+    timing(stat, ((Time.now - start) * 1000).round, sample_rate)
  40
+    result
  41
+  end
  42
+
36 43
   private
37 44
 
38 45
   def sampled(sample_rate)
24  spec/statsd_spec.rb
... ...
@@ -1,4 +1,4 @@
1  
-require 'spec/helper'
  1
+require 'helper'
2 2
 
3 3
 describe Statsd do
4 4
   before do
@@ -23,7 +23,6 @@ def socket; @socket ||= FakeUDPSocket.new end
23 23
     end
24 24
   end
25 25
 
26  
-
27 26
   describe "#increment" do
28 27
     it "should format the message according to the statsd spec" do
29 28
       @statsd.increment('foobar')
@@ -69,6 +68,27 @@ def socket; @socket ||= FakeUDPSocket.new end
69 68
     end
70 69
   end
71 70
 
  71
+  describe "#time" do
  72
+    it "should format the message according to the statsd spec" do
  73
+      @statsd.time('foobar') { sleep(0.001); 'test' }
  74
+      @statsd.socket.recv.must_equal ['foobar:1|ms']
  75
+    end
  76
+
  77
+    it "should return the result of the block" do
  78
+      result = @statsd.time('foobar') { sleep(0.001); 'test' }
  79
+      result.must_equal 'test'
  80
+    end
  81
+
  82
+    describe "with a sample rate" do
  83
+      before { class << @statsd; def rand; 0; end; end } # ensure delivery
  84
+
  85
+      it "should format the message according to the statsd spec" do
  86
+        result = @statsd.time('foobar', 0.5) { sleep(0.001); 'test' }
  87
+        @statsd.socket.recv.must_equal ['foobar:1|ms|@0.5']
  88
+      end
  89
+    end
  90
+  end
  91
+
72 92
   describe "#sampled" do
73 93
     describe "when the sample rate is 1" do
74 94
       it "should yield" do
Commit_comment_tip

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.