Permalink
Browse files

add Time function

  • Loading branch information...
1 parent 379b08c commit 0e2af589c1bbba16464f88e9a94a8803555d5d68 @cyberdelia committed Jul 14, 2012
Showing with 34 additions and 6 deletions.
  1. +12 −0 statsd.go
  2. +22 −6 statsd_test.go
View
12 statsd.go
@@ -7,13 +7,18 @@ import (
"io"
"math/rand"
"net"
+ "time"
)
type Client struct {
Name string
rw *bufio.ReadWriter
}
+func millisecond(d time.Duration) int {
+ return int(d.Seconds() * 1000)
+}
+
func Dial(addr string) (*Client, error) {
rw, err := net.Dial("udp", addr)
if err != nil {
@@ -41,6 +46,13 @@ func (c *Client) Timing(stat string, delta int, rate float64) error {
return c.Send(stat, rate, "%d|ms", delta)
}
+func (c *Client) Time(stat string, rate float64, f func()) error {
+ ts := time.Now()
+ f()
+ delta := millisecond(time.Now().Sub(ts))
+ return c.Timing(stat, delta, rate)
+}
+
func (c *Client) Send(stat string, rate float64, format string, args ...interface{}) error {
if rate < 1 {
if rand.Float64() < rate {
View
28 statsd_test.go
@@ -6,6 +6,7 @@ import (
"github.com/bmizerany/assert"
"io"
"testing"
+ "time"
)
type ReadWriter struct {
@@ -39,18 +40,33 @@ func TestDecrement(t *testing.T) {
assert.Equal(t, data, "decr:-1|c")
}
-func TestTiming(t *testing.T) {
+func TestIncrementRate(t *testing.T) {
c := newClient("<fake>", fake())
- err := c.Timing("time", 350, 1)
+ err := c.Increment("incr", 1, 0.99)
assert.Equal(t, err, nil)
data := readData(c.rw)
- assert.Equal(t, data, "time:350|ms")
+ assert.Equal(t, data, "incr:1|c|@0.99")
}
-func TestIncrementRate(t *testing.T) {
+func TestMilliseconds(t *testing.T) {
+ msec, _ := time.ParseDuration("350ms")
+ assert.Equal(t, 350, millisecond(msec))
+ sec, _ := time.ParseDuration("5s")
+ assert.Equal(t, 5000, millisecond(sec))
+ nsec, _ := time.ParseDuration("50ns")
+ assert.Equal(t, 0, millisecond(nsec))
+}
+
+func TestTiming(t *testing.T) {
c := newClient("<fake>", fake())
- err := c.Increment("incr", 1, 0.99)
+ err := c.Timing("timing", 350, 1)
assert.Equal(t, err, nil)
data := readData(c.rw)
- assert.Equal(t, data, "incr:1|c|@0.99")
+ assert.Equal(t, data, "timing:350|ms")
+}
+
+func TestTime(t *testing.T) {
+ c := newClient("<fake>", fake())
+ err := c.Time("time", 1, func() { time.Sleep(50e6) })
+ assert.Equal(t, err, nil)
}

0 comments on commit 0e2af58

Please sign in to comment.