github.com/psiphon-inc/goarista@v0.0.0-20160825065156-d002785f4c67/monitor/histogram.go (about) 1 // Copyright (C) 2015 Arista Networks, Inc. 2 // Use of this source code is governed by the Apache License 2.0 3 // that can be found in the COPYING file. 4 5 package monitor 6 7 import ( 8 "expvar" 9 "strings" 10 "time" 11 12 "github.com/aristanetworks/goarista/monitor/stats" 13 ) 14 15 // Histogram contains the data needed to properly export itself to expvar 16 // and provide a pretty printed version 17 type Histogram struct { 18 name string 19 histogram *stats.Histogram 20 } 21 22 // NewHistogram creates a new histogram and registers an HTTP handler for it. 23 // "name" must end with "Histogram", so that the "/debug/latency" handler can 24 // pretty print it. 25 func NewHistogram(name string, numBuckets int, growth float64, smallest float64, 26 minValue int64) *Histogram { 27 28 histogramOptions := stats.HistogramOptions{ 29 NumBuckets: numBuckets, 30 GrowthFactor: growth, 31 SmallestBucketSize: smallest, 32 MinValue: minValue, 33 } 34 35 hist := stats.NewHistogram(histogramOptions) 36 histogram := &Histogram{ 37 name: name, 38 histogram: hist, 39 } 40 expvar.Publish(name, histogram) 41 return histogram 42 43 } 44 45 func (h *Histogram) String() string { 46 return h.addUnits(h.histogram.Delta1m().String()) + 47 h.addUnits(h.histogram.Delta10m().String()) + 48 h.addUnits(h.histogram.Delta1h().String()) + 49 h.addUnits(h.histogram.Value().String()) 50 } 51 52 // UpdateLatencyValues updates the stats.Histogram's buckets with the new 53 // datapoint and updates the string associated with the expvar.String 54 func (h *Histogram) UpdateLatencyValues(t0, t1 time.Time) { 55 h.histogram.Add(int64(t1.Sub(t0) / time.Microsecond)) 56 } 57 58 func (h *Histogram) addUnits(hist string) string { 59 i := strings.Index(hist, "\n") 60 return hist[:i] + "µs" + hist[i:] 61 }