Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize counter inc-by-one #109

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions spectator/meter/counter.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ import (
//
// https://netflix.github.io/spectator/en/latest/intro/counter/
type Counter struct {
id *Id
writer writer.Writer
meterTypeSymbol string
id *Id
writer writer.Writer
incByOneLine string
}

// NewCounter generates a new counter, using the provided meter identifier.
func NewCounter(id *Id, writer writer.Writer) *Counter {
return &Counter{id, writer, "c"}
return &Counter{id, writer, fmt.Sprintf("c:%s:1", id.spectatordId)}
}

// MeterId returns the meter identifier.
Expand All @@ -30,22 +30,25 @@ func (c *Counter) MeterId() *Id {

// Increment increments the counter.
func (c *Counter) Increment() {
var line = fmt.Sprintf("%s:%s:%d", c.meterTypeSymbol, c.id.spectatordId, 1)
c.writer.Write(line)
c.writer.Write(c.incByOneLine)
}

// Add adds an int64 delta to the current measurement.
func (c *Counter) Add(delta int64) {
if delta == 1 {
c.writer.Write(c.incByOneLine)
return
}
if delta > 0 {
var line = fmt.Sprintf("%s:%s:%d", c.meterTypeSymbol, c.id.spectatordId, delta)
var line = fmt.Sprintf("c:%s:%d", c.id.spectatordId, delta)
c.writer.Write(line)
}
}

// AddFloat adds a float64 delta to the current measurement.
func (c *Counter) AddFloat(delta float64) {
if delta > 0.0 {
var line = fmt.Sprintf("%s:%s:%f", c.meterTypeSymbol, c.id.spectatordId, delta)
var line = fmt.Sprintf("c:%s:%f", c.id.spectatordId, delta)
c.writer.Write(line)
}
}
12 changes: 9 additions & 3 deletions spectator/meter/counter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,21 @@ func TestCounter_Add(t *testing.T) {
id := NewId("add", nil)
c := NewCounter(id, &w)

c.Add(4)
c.Add(1)

expected := "c:add:4"
expected := "c:add:1"
if w.Lines()[0] != expected {
t.Error("Expected ", expected, " got ", w.Lines()[0])
}
c.Add(4)

expected = "c:add:4"
if w.Lines()[1] != expected {
t.Error("Expected ", expected, " got ", w.Lines()[1])
}

c.Add(-1)
if len(w.Lines()) != 1 {
if len(w.Lines()) != 2 {
t.Error("Negative deltas should be ignored")
}
}
Expand Down