pax_global_header00006660000000000000000000000064131336175450014522gustar00rootroot0000000000000052 comment=524851a93235ac051e3540563ed7909357fe24ab ratecounter-0.2.0/000077500000000000000000000000001313361754500140545ustar00rootroot00000000000000ratecounter-0.2.0/.gitignore000066400000000000000000000004031313361754500160410ustar00rootroot00000000000000# Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *.sw? ratecounter-0.2.0/CONTRIBUTORS.md000066400000000000000000000005441313361754500163360ustar00rootroot00000000000000RateCounter Contributors (sorted alphabetically) ============================================ - **[cheshir](https://github.com/cheshir)** - Added averate rate counter - **[paulbellamy](https://github.com/paulbellamy)** - Original implementation and general housekeeping - **[sheerun](https://github.com/sheerun)** - Improved memory efficiency ratecounter-0.2.0/LICENSE000066400000000000000000000020431313361754500150600ustar00rootroot00000000000000Copyright (C) 2012 by Paul Bellamy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ratecounter-0.2.0/README.md000066400000000000000000000036131313361754500153360ustar00rootroot00000000000000# ratecounter [![CircleCI](https://circleci.com/gh/paulbellamy/ratecounter.svg?style=svg)](https://circleci.com/gh/paulbellamy/ratecounter) [![Go Report Card](https://goreportcard.com/badge/github.com/paulbellamy/ratecounter)](https://goreportcard.com/report/github.com/paulbellamy/ratecounter) [![GoDoc](https://godoc.org/github.com/paulbellamy/ratecounter?status.svg)](https://godoc.org/github.com/paulbellamy/ratecounter) [![codecov](https://codecov.io/gh/paulbellamy/ratecounter/branch/master/graph/badge.svg)](https://codecov.io/gh/paulbellamy/ratecounter) A Thread-Safe RateCounter implementation in Golang ## Usage ``` import "github.com/paulbellamy/ratecounter" ``` Package ratecounter provides a thread-safe rate-counter, for tracking counts in an interval Useful for implementing counters and stats of 'requests-per-second' (for example): ```go // We're recording marks-per-1second counter := ratecounter.NewRateCounter(1 * time.Second) // Record an event happening counter.Incr(1) // get the current requests-per-second counter.Rate() ``` To record an average over a longer period, you can: ```go // Record requests-per-minute counter := ratecounter.NewRateCounter(60 * time.Second) // Calculate the average requests-per-second for the last minute counter.Rate() / 60 ``` Also you can track average value of some metric in an interval. Useful for implementing counters and stats of 'average-execution-time' (for example): ```go // We're recording average execution time of some heavy operation in the last minute. counter := ratecounter.NewAvgRateCounter(60 * time.Second) // Start timer. startTime := time.Now() // Execute heavy operation. heavyOperation() // Record elapsed time. counter.Incr(time.Since(startTime).Nanoseconds()) // Get the current average execution time. counter.Rate() ``` ## Documentation Check latest documentation on [go doc](https://godoc.org/github.com/paulbellamy/ratecounter). ratecounter-0.2.0/avgratecounter.go000066400000000000000000000031141313361754500174330ustar00rootroot00000000000000package ratecounter import ( "strconv" "time" ) // An AvgRateCounter is a thread-safe counter which returns // the ratio between the number of calls 'Incr' and the counter value in the last interval type AvgRateCounter struct { hits *RateCounter counter *RateCounter interval time.Duration } // NewAvgRateCounter constructs a new AvgRateCounter, for the interval provided func NewAvgRateCounter(intrvl time.Duration) *AvgRateCounter { return &AvgRateCounter{ hits: NewRateCounter(intrvl), counter: NewRateCounter(intrvl), interval: intrvl, } } // WithResolution determines the minimum resolution of this counter func (a *AvgRateCounter) WithResolution(resolution int) *AvgRateCounter { if resolution < 1 { panic("AvgRateCounter resolution cannot be less than 1") } a.hits = a.hits.WithResolution(resolution) a.counter = a.counter.WithResolution(resolution) return a } // Incr Adds an event into the AvgRateCounter func (a *AvgRateCounter) Incr(val int64) { a.hits.Incr(1) a.counter.Incr(val) } // Rate Returns the current ratio between the events count and its values during the last interval func (a *AvgRateCounter) Rate() float64 { hits, value := a.hits.Rate(), a.counter.Rate() if hits == 0 { return 0 // Avoid division by zero } return float64(value) / float64(hits) } // Hits returns the number of calling method Incr during specified interval func (a *AvgRateCounter) Hits() int64 { return a.hits.Rate() } // String returns counter's rate formatted to string func (a *AvgRateCounter) String() string { return strconv.FormatFloat(a.Rate(), 'e', 5, 64) } ratecounter-0.2.0/avgratecounter_test.go000066400000000000000000000036431313361754500205010ustar00rootroot00000000000000package ratecounter import ( "testing" "time" ) func TestAvgRateCounter(t *testing.T) { interval := 500 * time.Millisecond r := NewAvgRateCounter(interval) check := func(expected float64) { val := r.Rate() if val != expected { t.Error("Expected ", val, " to equal ", expected) } } check(0) r.Incr(1) // counter = 1, hits = 1 check(1.0) r.Incr(3) // counter = 4, hits = 2 check(2.0) time.Sleep(2 * interval) check(0) } func TestAvgRateCounterAdvanced(t *testing.T) { interval := 500 * time.Millisecond almost := 450 * time.Millisecond r := NewAvgRateCounter(interval) check := func(expected float64) { val := r.Rate() if val != expected { t.Error("Expected ", val, " to equal ", expected) } } check(0) r.Incr(1) // counter = 1, hits = 1 check(1.0) time.Sleep(interval - almost) r.Incr(3) // counter = 4, hits = 2 check(2.0) time.Sleep(almost) check(3.0) // counter = 3, hits = 1 time.Sleep(2 * interval) check(0) } func TestAvgRateCounterNoResolution(t *testing.T) { interval := 500 * time.Millisecond almost := 450 * time.Millisecond r := NewAvgRateCounter(interval).WithResolution(1) check := func(expected float64) { val := r.Rate() if val != expected { t.Error("Expected ", val, " to equal ", expected) } } check(0) r.Incr(1) // counter = 1, hits = 1 check(1.0) time.Sleep(interval - almost) r.Incr(3) // counter = 4, hits = 2 check(2.0) time.Sleep(almost) check(0) // counter = 0, hits = 0 time.Sleep(2 * interval) check(0) } func TestAvgRateCounter_Incr_ReturnsImmediately(t *testing.T) { interval := 1 * time.Second r := NewRateCounter(interval) start := time.Now() r.Incr(-1) duration := time.Since(start) if duration >= 1*time.Second { t.Error("incr took", duration, "to return") } } func BenchmarkAvgRateCounter(b *testing.B) { interval := 0 * time.Millisecond r := NewAvgRateCounter(interval) for i := 0; i < b.N; i++ { r.Incr(1) r.Rate() } } ratecounter-0.2.0/circle.yml000066400000000000000000000007731313361754500160470ustar00rootroot00000000000000dependencies: post: - go get -u github.com/alecthomas/gometalinter - gometalinter --install test: override: - go test -v -race -coverprofile=coverage.txt -covermode=atomic ./... - | gometalinter \ --disable-all \ --enable=deadcode \ --enable=errcheck \ --enable=golint \ --enable=gosimple \ --enable=unconvert \ --enable=vet \ --enable=vetshadow \ ./... post: - bash <(curl -s https://codecov.io/bash) ratecounter-0.2.0/counter.go000066400000000000000000000007451313361754500160700ustar00rootroot00000000000000package ratecounter import "sync/atomic" // A Counter is a thread-safe counter implementation type Counter int64 // Incr method increments the counter by some value func (c *Counter) Incr(val int64) { atomic.AddInt64((*int64)(c), val) } // Reset method resets the counter's value to zero func (c *Counter) Reset() { atomic.StoreInt64((*int64)(c), 0) } // Value method returns the counter's current value func (c *Counter) Value() int64 { return atomic.LoadInt64((*int64)(c)) } ratecounter-0.2.0/counter_test.go000066400000000000000000000010671313361754500171250ustar00rootroot00000000000000package ratecounter import ( "sync" "testing" ) func TestCounter(t *testing.T) { var c Counter check := func(expected int64) { val := c.Value() if val != expected { t.Error("Expected ", val, " to equal ", expected) } } check(0) c.Incr(1) check(1) c.Incr(9) check(10) // Concurrent usage wg := &sync.WaitGroup{} wg.Add(3) for i := 1; i <= 3; i++ { go func(val int64) { c.Incr(val) wg.Done() }(int64(i)) } wg.Wait() check(16) } func BenchmarkCounter(b *testing.B) { var c Counter for i := 0; i < b.N; i++ { c.Incr(1) } } ratecounter-0.2.0/doc.go000066400000000000000000000012011313361754500151420ustar00rootroot00000000000000/* Package ratecounter provides a thread-safe rate-counter, for tracking counts in an interval Useful for implementing counters and stats of 'requests-per-second' (for example). // We're recording marks-per-1second counter := ratecounter.NewRateCounter(1 * time.Second) // Record an event happening counter.Mark() // get the current requests-per-second counter.Rate() To record an average over a longer period, you can: // Record requests-per-minute counter := ratecounter.NewRateCounter(60 * time.Second) // Calculate the average requests-per-second for the last minute counter.Rate() / 60 */ package ratecounter ratecounter-0.2.0/ratecounter.go000066400000000000000000000035211313361754500167370ustar00rootroot00000000000000package ratecounter import ( "strconv" "sync/atomic" "time" ) // A RateCounter is a thread-safe counter which returns the number of times // 'Incr' has been called in the last interval type RateCounter struct { counter Counter interval time.Duration resolution int partials []Counter current int32 running int32 } // NewRateCounter Constructs a new RateCounter, for the interval provided func NewRateCounter(intrvl time.Duration) *RateCounter { ratecounter := &RateCounter{ interval: intrvl, running: 0, } return ratecounter.WithResolution(20) } // WithResolution determines the minimum resolution of this counter, default is 20 func (r *RateCounter) WithResolution(resolution int) *RateCounter { if resolution < 1 { panic("RateCounter resolution cannot be less than 1") } r.resolution = resolution r.partials = make([]Counter, resolution) r.current = 0 return r } func (r *RateCounter) run() { if ok := atomic.CompareAndSwapInt32(&r.running, 0, 1); !ok { return } go func() { ticker := time.NewTicker(time.Duration(float64(r.interval) / float64(r.resolution))) for range ticker.C { current := atomic.LoadInt32(&r.current) next := (int(current) + 1) % r.resolution r.counter.Incr(-1 * r.partials[next].Value()) r.partials[next].Reset() atomic.CompareAndSwapInt32(&r.current, current, int32(next)) if r.counter.Value() == 0 { atomic.StoreInt32(&r.running, 0) ticker.Stop() return } } }() } // Incr Add an event into the RateCounter func (r *RateCounter) Incr(val int64) { r.counter.Incr(val) r.partials[atomic.LoadInt32(&r.current)].Incr(val) r.run() } // Rate Return the current number of events in the last interval func (r *RateCounter) Rate() int64 { return r.counter.Value() } func (r *RateCounter) String() string { return strconv.FormatInt(r.counter.Value(), 10) } ratecounter-0.2.0/ratecounter_test.go000066400000000000000000000077061313361754500200070ustar00rootroot00000000000000package ratecounter import ( "fmt" "io/ioutil" "testing" "time" ) func TestRateCounter(t *testing.T) { interval := 500 * time.Millisecond r := NewRateCounter(interval) check := func(expected int64) { val := r.Rate() if val != expected { t.Error("Expected ", val, " to equal ", expected) } } check(0) r.Incr(1) check(1) r.Incr(2) check(3) time.Sleep(2 * interval) check(0) } func TestRateCounterResetAndRestart(t *testing.T) { interval := 100 * time.Millisecond r := NewRateCounter(interval) check := func(expected int64) { val := r.Rate() if val != expected { t.Error("Expected ", val, " to equal ", expected) } } check(0) r.Incr(1) check(1) time.Sleep(2 * interval) check(0) time.Sleep(2 * interval) r.Incr(2) check(2) time.Sleep(2 * interval) check(0) r.Incr(2) check(2) } func TestRateCounterPartial(t *testing.T) { interval := 500 * time.Millisecond almostinterval := 400 * time.Millisecond r := NewRateCounter(interval) check := func(expected int64) { val := r.Rate() if val != expected { t.Error("Expected ", val, " to equal ", expected) } } check(0) r.Incr(1) check(1) time.Sleep(almostinterval) r.Incr(2) check(3) time.Sleep(almostinterval) check(2) time.Sleep(2 * interval) check(0) } func TestRateCounterHighResolution(t *testing.T) { interval := 500 * time.Millisecond tenth := 50 * time.Millisecond r := NewRateCounter(interval).WithResolution(100) check := func(expected int64) { val := r.Rate() if val != expected { t.Error("Expected ", val, " to equal ", expected) } } check(0) r.Incr(1) check(1) time.Sleep(2 * tenth) r.Incr(1) check(2) time.Sleep(2 * tenth) r.Incr(1) check(3) time.Sleep(interval - 5*tenth) check(3) time.Sleep(2 * tenth) check(2) time.Sleep(2 * tenth) check(1) time.Sleep(2 * tenth) check(0) } func TestRateCounterLowResolution(t *testing.T) { interval := 500 * time.Millisecond tenth := 50 * time.Millisecond r := NewRateCounter(interval).WithResolution(4) check := func(expected int64) { val := r.Rate() if val != expected { t.Error("Expected ", val, " to equal ", expected) } } check(0) r.Incr(1) check(1) time.Sleep(2 * tenth) r.Incr(1) check(2) time.Sleep(2 * tenth) r.Incr(1) check(3) time.Sleep(interval - 5*tenth) check(3) time.Sleep(2 * tenth) check(1) time.Sleep(2 * tenth) check(0) time.Sleep(2 * tenth) check(0) } func TestRateCounterNoResolution(t *testing.T) { interval := 500 * time.Millisecond tenth := 50 * time.Millisecond r := NewRateCounter(interval).WithResolution(1) check := func(expected int64) { val := r.Rate() if val != expected { t.Error("Expected ", val, " to equal ", expected) } } check(0) r.Incr(1) check(1) time.Sleep(2 * tenth) r.Incr(1) check(2) time.Sleep(2 * tenth) r.Incr(1) check(3) time.Sleep(interval - 5*tenth) check(3) time.Sleep(2 * tenth) check(0) time.Sleep(2 * tenth) check(0) time.Sleep(2 * tenth) check(0) } func TestRateCounter_Incr_ReturnsImmediately(t *testing.T) { interval := 1 * time.Second r := NewRateCounter(interval) start := time.Now() r.Incr(-1) duration := time.Since(start) if duration >= 1*time.Second { t.Error("incr took", duration, "to return") } } func BenchmarkRateCounter(b *testing.B) { interval := 0 * time.Millisecond r := NewRateCounter(interval) for i := 0; i < b.N; i++ { r.Incr(1) r.Rate() } } func BenchmarkRateCounter_Parallel(b *testing.B) { interval := 0 * time.Millisecond r := NewRateCounter(interval) b.RunParallel(func(pb *testing.PB) { for pb.Next() { r.Incr(1) r.Rate() } }) } func BenchmarkRateCounter_With5MillionExisting(b *testing.B) { interval := 1 * time.Hour r := NewRateCounter(interval) for i := 0; i < 5000000; i++ { r.Incr(1) } b.ResetTimer() for i := 0; i < b.N; i++ { r.Incr(1) r.Rate() } } func Benchmark_TimeNowAndAdd(b *testing.B) { var a time.Time for i := 0; i < b.N; i++ { a = time.Now().Add(1 * time.Second) } fmt.Fprintln(ioutil.Discard, a) }