histogram.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. package monitor
  5. import (
  6. "expvar"
  7. "strings"
  8. "time"
  9. "notabug.org/themusicgod1/goarista/monitor/stats"
  10. )
  11. // LatencyHistogram contains the data needed to properly export itself to expvar
  12. // and provide a pretty printed version
  13. type LatencyHistogram struct {
  14. name string
  15. histogram *stats.Histogram
  16. latencyUnit time.Duration
  17. }
  18. // NewLatencyHistogram creates a new histogram and registers an HTTP handler for it.
  19. func NewLatencyHistogram(name string, latencyUnit time.Duration, numBuckets int,
  20. growth float64, smallest float64, minValue int64) *LatencyHistogram {
  21. histogramOptions := stats.HistogramOptions{
  22. NumBuckets: numBuckets,
  23. GrowthFactor: growth,
  24. SmallestBucketSize: smallest,
  25. MinValue: minValue,
  26. }
  27. histogram := &LatencyHistogram{
  28. name: name,
  29. histogram: stats.NewHistogram(histogramOptions),
  30. latencyUnit: latencyUnit,
  31. }
  32. expvar.Publish(name, histogram)
  33. return histogram
  34. }
  35. // Print returns the histogram as a chart
  36. func (h *LatencyHistogram) Print() string {
  37. return h.addUnits(h.histogram.Delta1m().String()) +
  38. h.addUnits(h.histogram.Delta10m().String()) +
  39. h.addUnits(h.histogram.Delta1h().String()) +
  40. h.addUnits(h.histogram.Value().String())
  41. }
  42. // String returns the histogram as JSON.
  43. func (h *LatencyHistogram) String() string {
  44. return h.histogram.String()
  45. }
  46. // UpdateLatencyValues updates the LatencyHistogram's buckets with the new
  47. // datapoint and updates the string associated with the expvar.String
  48. func (h *LatencyHistogram) UpdateLatencyValues(delta time.Duration) {
  49. h.histogram.Add(int64(delta / h.latencyUnit))
  50. }
  51. func (h *LatencyHistogram) addUnits(hist string) string {
  52. i := strings.Index(hist, "\n")
  53. return hist[:i] + "µs" + hist[i:]
  54. }