sample.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. package metrics
  2. import (
  3. "rand"
  4. )
  5. type Sample interface {
  6. Clear()
  7. Count() int
  8. Size() int
  9. Update(int64)
  10. Values() []int64
  11. }
  12. type expDecaySample struct {
  13. reservoirSize int
  14. alpha float64
  15. count int
  16. values []int64
  17. }
  18. func NewExpDecaySample(reservoirSize int, alpha float64) Sample {
  19. return &expDecaySample{
  20. reservoirSize, alpha,
  21. 0,
  22. make([]int64, reservoirSize),
  23. }
  24. }
  25. func (s *expDecaySample) Clear() {
  26. }
  27. func (s *expDecaySample) Count() int {
  28. return s.count
  29. }
  30. func (s *expDecaySample) Size() int {
  31. return 0
  32. }
  33. func (s *expDecaySample) Update(v int64) {
  34. }
  35. func (s *expDecaySample) Values() []int64 {
  36. return s.values // It might be worth copying this before returning it.
  37. }
  38. type uniformSample struct {
  39. reservoirSize int
  40. in chan int64
  41. out chan sampleV
  42. reset chan bool
  43. }
  44. func NewUniformSample(reservoirSize int) Sample {
  45. s := &uniformSample{
  46. reservoirSize,
  47. make(chan int64),
  48. make(chan sampleV),
  49. make(chan bool),
  50. }
  51. go s.arbiter()
  52. return s
  53. }
  54. func (s *uniformSample) Clear() {
  55. s.reset <- true
  56. }
  57. func (s *uniformSample) Count() int {
  58. return (<-s.out).count
  59. }
  60. func (s *uniformSample) Size() int {
  61. return (<-s.out).size()
  62. }
  63. func (s *uniformSample) Update(v int64) {
  64. s.in <- v
  65. }
  66. func (s *uniformSample) Values() []int64 {
  67. return (<-s.out).values
  68. }
  69. func (s *uniformSample) arbiter() {
  70. sv := newSampleV(s.reservoirSize)
  71. for {
  72. select {
  73. case v := <-s.in:
  74. sv.count++
  75. if sv.count < s.reservoirSize {
  76. sv.values[sv.count - 1] = v
  77. } else {
  78. sv.values[rand.Intn(s.reservoirSize)] = v
  79. }
  80. case s.out <- sv.dup():
  81. case <-s.reset:
  82. for i, _ := range sv.values { sv.values[i] = 0 }
  83. }
  84. }
  85. }
  86. type sampleV struct {
  87. count int
  88. values []int64
  89. }
  90. func newSampleV(reservoirSize int) sampleV {
  91. return sampleV{0, make([]int64, reservoirSize)}
  92. }
  93. func (sv sampleV) dup() sampleV {
  94. values := make([]int64, sv.size())
  95. for i := 0; i < sv.size(); i++ { values[i] = sv.values[i] }
  96. return sampleV{sv.count, values}
  97. }
  98. func (sv sampleV) size() int {
  99. if sv.count < len(sv.values) {
  100. return sv.count
  101. }
  102. return len(sv.values)
  103. }