Skip to content

Instantly share code, notes, and snippets.

@karlseguin
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlseguin/8877070 to your computer and use it in GitHub Desktop.
Save karlseguin/8877070 to your computer and use it in GitHub Desktop.
Track data points with constant-space via sampling (can be used to calculate percentiles, for example)
const (
MAX_SAMPLE_COUNT = 50
MAX_SAMPLE_COUNT_F = float64(MAX_SAMPLE_COUNT)
)
type Stat struct {
sync.Mutex
hits int64
samples []int
}
func (s *Stat) Timing(t int) {
index := -1
hits := atomic.AddInt64(&s.hits, 1)
if hits < MAX_SAMPLE_COUNT {
index = int(hits)
} else if MAX_SAMPLE_COUNT_F / float64(hits) > rand.Float64() {
index = int(rand.Int31n(MAX_SAMPLE_COUNT))
}
if index != -1 {
s.Lock()
s.samples[index] = t
s.Unlock()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment