sample.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. package metrics
  2. import (
  3. "container/heap"
  4. "math"
  5. "math/rand"
  6. "sort"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. )
  11. const rescaleThreshold = time.Hour
  12. // Samples maintain a statistically-significant selection of values from
  13. // a stream.
  14. //
  15. // This is an interface so as to encourage other structs to implement
  16. // the Sample API as appropriate.
  17. type Sample interface {
  18. Clear()
  19. Count() int64
  20. Dup() Sample
  21. Max() int64
  22. Mean() float64
  23. Min() int64
  24. Percentile(float64) float64
  25. Percentiles([]float64) []float64
  26. Size() int
  27. StdDev() float64
  28. Update(int64)
  29. Values() []int64
  30. Variance() float64
  31. }
  32. // ExpDecaySample is an exponentially-decaying sample using a forward-decaying
  33. // priority reservoir. See Cormode et al's "Forward Decay: A Practical Time
  34. // Decay Model for Streaming Systems".
  35. //
  36. // <http://www.research.att.com/people/Cormode_Graham/library/publications/CormodeShkapenyukSrivastavaXu09.pdf>
  37. type ExpDecaySample struct {
  38. alpha float64
  39. count int64
  40. mutex sync.Mutex
  41. reservoirSize int
  42. t0, t1 time.Time
  43. values expDecaySampleHeap
  44. }
  45. // NewExpDecaySample constructs a new exponentially-decaying sample with the
  46. // given reservoir size and alpha.
  47. func NewExpDecaySample(reservoirSize int, alpha float64) Sample {
  48. if UseNilMetrics {
  49. return NilSample{}
  50. }
  51. s := &ExpDecaySample{
  52. alpha: alpha,
  53. reservoirSize: reservoirSize,
  54. t0: time.Now(),
  55. values: make(expDecaySampleHeap, 0, reservoirSize),
  56. }
  57. s.t1 = time.Now().Add(rescaleThreshold)
  58. return s
  59. }
  60. // Clear clears all samples.
  61. func (s *ExpDecaySample) Clear() {
  62. s.mutex.Lock()
  63. defer s.mutex.Unlock()
  64. s.count = 0
  65. s.t0 = time.Now()
  66. s.t1 = s.t0.Add(rescaleThreshold)
  67. s.values = make(expDecaySampleHeap, 0, s.reservoirSize)
  68. }
  69. // Dup returns a copy of the sample.
  70. func (s *ExpDecaySample) Dup() Sample {
  71. s.mutex.Lock()
  72. defer s.mutex.Unlock()
  73. values := make(expDecaySampleHeap, len(s.values))
  74. copy(values, s.values)
  75. return &ExpDecaySample{
  76. alpha: s.alpha,
  77. count: s.count,
  78. reservoirSize: s.reservoirSize,
  79. t0: s.t0,
  80. t1: s.t1,
  81. values: values,
  82. }
  83. }
  84. // Count returns the number of samples recorded, which may exceed the
  85. // reservoir size.
  86. func (s *ExpDecaySample) Count() int64 {
  87. return atomic.LoadInt64(&s.count)
  88. }
  89. // Max returns the maximum value in the sample, which may not be the maximum
  90. // value ever to be part of the sample.
  91. func (s *ExpDecaySample) Max() int64 {
  92. return max(s.Values())
  93. }
  94. // Return the mean of all values seen since the histogram was last cleared.
  95. func (s *ExpDecaySample) Mean() float64 {
  96. return mean(s.Values())
  97. }
  98. // Min returns the minimum value in the sample, which may not be the minimum
  99. // value ever to be part of the sample.
  100. func (s *ExpDecaySample) Min() int64 {
  101. return min(s.Values())
  102. }
  103. // Percentile returns an arbitrary percentile of sampled values.
  104. func (s *ExpDecaySample) Percentile(p float64) float64 {
  105. return s.Percentiles([]float64{p})[0]
  106. }
  107. // Percentiles returns a slice of arbitrary percentiles of sampled values.
  108. func (s *ExpDecaySample) Percentiles(ps []float64) []float64 {
  109. return percentiles(s.Values(), ps)
  110. }
  111. // Size returns the size of the sample, which is at most the reservoir size.
  112. func (s *ExpDecaySample) Size() int {
  113. s.mutex.Lock()
  114. defer s.mutex.Unlock()
  115. return len(s.values)
  116. }
  117. // StdDev returns the standard deviation of the sample.
  118. func (s *ExpDecaySample) StdDev() float64 {
  119. return math.Sqrt(s.Variance())
  120. }
  121. // Update samples a new value.
  122. func (s *ExpDecaySample) Update(v int64) {
  123. s.update(time.Now(), v)
  124. }
  125. // Values returns a copy of the values in the sample.
  126. func (s *ExpDecaySample) Values() []int64 {
  127. s.mutex.Lock()
  128. defer s.mutex.Unlock()
  129. values := make([]int64, len(s.values))
  130. for i, v := range s.values {
  131. values[i] = v.v
  132. }
  133. return values
  134. }
  135. // Variance returns the variance of the sample.
  136. func (s *ExpDecaySample) Variance() float64 {
  137. return variance(s.Values())
  138. }
  139. // update samples a new value at a particular timestamp. This is a method all
  140. // its own to facilitate testing.
  141. func (s *ExpDecaySample) update(t time.Time, v int64) {
  142. s.mutex.Lock()
  143. defer s.mutex.Unlock()
  144. s.count++
  145. if len(s.values) == s.reservoirSize {
  146. heap.Pop(&s.values)
  147. }
  148. heap.Push(&s.values, expDecaySample{
  149. k: math.Exp(t.Sub(s.t0).Seconds()*s.alpha) / rand.Float64(),
  150. v: v,
  151. })
  152. if t.After(s.t1) {
  153. values := s.values
  154. t0 := s.t0
  155. s.values = make(expDecaySampleHeap, 0, s.reservoirSize)
  156. s.t0 = t
  157. s.t1 = s.t0.Add(rescaleThreshold)
  158. for _, v := range values {
  159. v.k = v.k * math.Exp(-s.alpha*float64(s.t0.Sub(t0)))
  160. heap.Push(&s.values, v)
  161. }
  162. }
  163. }
  164. // No-op Sample.
  165. type NilSample struct{}
  166. // No-op.
  167. func (NilSample) Clear() {}
  168. // No-op.
  169. func (NilSample) Count() int64 { return 0 }
  170. // No-op.
  171. func (NilSample) Dup() Sample { return NilSample{} }
  172. // No-op.
  173. func (NilSample) Max() int64 { return 0 }
  174. // No-op.
  175. func (NilSample) Mean() float64 { return 0.0 }
  176. // No-op.
  177. func (NilSample) Min() int64 { return 0 }
  178. // No-op.
  179. func (NilSample) Percentile(p float64) float64 { return 0.0 }
  180. // No-op.
  181. func (NilSample) Percentiles(ps []float64) []float64 {
  182. return make([]float64, len(ps))
  183. }
  184. // No-op.
  185. func (NilSample) Size() int { return 0 }
  186. // No-op.
  187. func (NilSample) StdDev() float64 { return 0.0 }
  188. // No-op.
  189. func (NilSample) Update(v int64) {}
  190. // No-op.
  191. func (NilSample) Values() []int64 { return []int64{} }
  192. // No-op.
  193. func (NilSample) Variance() float64 { return 0.0 }
  194. // A uniform sample using Vitter's Algorithm R.
  195. //
  196. // <http://www.cs.umd.edu/~samir/498/vitter.pdf>
  197. type UniformSample struct {
  198. count int64
  199. mutex sync.Mutex
  200. reservoirSize int
  201. values []int64
  202. }
  203. // Create a new uniform sample with the given reservoir size.
  204. func NewUniformSample(reservoirSize int) Sample {
  205. if UseNilMetrics {
  206. return NilSample{}
  207. }
  208. return &UniformSample{reservoirSize: reservoirSize}
  209. }
  210. // Clear all samples.
  211. func (s *UniformSample) Clear() {
  212. s.mutex.Lock()
  213. defer s.mutex.Unlock()
  214. s.count = 0
  215. s.values = make([]int64, 0, s.reservoirSize)
  216. }
  217. // Count returns the number of samples recorded, which may exceed the
  218. // reservoir size.
  219. func (s *UniformSample) Count() int64 {
  220. return atomic.LoadInt64(&s.count)
  221. }
  222. // Dup returns a copy of the sample.
  223. func (s *UniformSample) Dup() Sample {
  224. s.mutex.Lock()
  225. defer s.mutex.Unlock()
  226. values := make([]int64, len(s.values))
  227. copy(values, s.values)
  228. return &UniformSample{
  229. count: s.count,
  230. reservoirSize: s.reservoirSize,
  231. values: values,
  232. }
  233. }
  234. // Max returns the maximum value in the sample, which may not be the maximum
  235. // value ever to be part of the sample.
  236. func (s *UniformSample) Max() int64 {
  237. s.mutex.Lock()
  238. defer s.mutex.Unlock()
  239. return max(s.values)
  240. }
  241. // Return the mean of all values seen since the histogram was last cleared.
  242. func (s *UniformSample) Mean() float64 {
  243. s.mutex.Lock()
  244. defer s.mutex.Unlock()
  245. return mean(s.values)
  246. }
  247. // Min returns the minimum value in the sample, which may not be the minimum
  248. // value ever to be part of the sample.
  249. func (s *UniformSample) Min() int64 {
  250. s.mutex.Lock()
  251. defer s.mutex.Unlock()
  252. return min(s.values)
  253. }
  254. // Percentile returns an arbitrary percentile of sampled values.
  255. func (s *UniformSample) Percentile(p float64) float64 {
  256. return s.Percentiles([]float64{p})[0]
  257. }
  258. // Percentiles returns a slice of arbitrary percentiles of sampled values.
  259. func (s *UniformSample) Percentiles(ps []float64) []float64 {
  260. s.mutex.Lock()
  261. defer s.mutex.Unlock()
  262. return percentiles(s.values, ps)
  263. }
  264. // Return the size of the sample, which is at most the reservoir size.
  265. func (s *UniformSample) Size() int {
  266. s.mutex.Lock()
  267. defer s.mutex.Unlock()
  268. return len(s.values)
  269. }
  270. // StdDev returns the standard deviation of the sample.
  271. func (s *UniformSample) StdDev() float64 {
  272. return math.Sqrt(s.Variance())
  273. }
  274. // Update the sample with a new value.
  275. func (s *UniformSample) Update(v int64) {
  276. s.mutex.Lock()
  277. defer s.mutex.Unlock()
  278. s.count++
  279. if len(s.values) < s.reservoirSize {
  280. s.values = append(s.values, v)
  281. } else {
  282. s.values[rand.Intn(s.reservoirSize)] = v
  283. }
  284. }
  285. // Return all the values in the sample.
  286. func (s *UniformSample) Values() []int64 {
  287. s.mutex.Lock()
  288. defer s.mutex.Unlock()
  289. values := make([]int64, len(s.values))
  290. copy(values, s.values)
  291. return values
  292. }
  293. // Variance returns the variance of the sample.
  294. func (s *UniformSample) Variance() float64 {
  295. s.mutex.Lock()
  296. defer s.mutex.Unlock()
  297. return variance(s.values)
  298. }
  299. // expDecaySample represents an individual sample in a heap.
  300. type expDecaySample struct {
  301. k float64
  302. v int64
  303. }
  304. // expDecaySampleHeap is a min-heap of expDecaySamples.
  305. type expDecaySampleHeap []expDecaySample
  306. func (q expDecaySampleHeap) Len() int {
  307. return len(q)
  308. }
  309. func (q expDecaySampleHeap) Less(i, j int) bool {
  310. return q[i].k < q[j].k
  311. }
  312. func (q *expDecaySampleHeap) Pop() interface{} {
  313. q_ := *q
  314. n := len(q_)
  315. i := q_[n-1]
  316. q_ = q_[0 : n-1]
  317. *q = q_
  318. return i
  319. }
  320. func (q *expDecaySampleHeap) Push(x interface{}) {
  321. q_ := *q
  322. n := len(q_)
  323. q_ = q_[0 : n+1]
  324. q_[n] = x.(expDecaySample)
  325. *q = q_
  326. }
  327. func (q expDecaySampleHeap) Swap(i, j int) {
  328. q[i], q[j] = q[j], q[i]
  329. }
  330. func max(values []int64) int64 {
  331. if 0 == len(values) {
  332. return 0
  333. }
  334. var max int64 = math.MinInt64
  335. for _, v := range values {
  336. if max < v {
  337. max = v
  338. }
  339. }
  340. return max
  341. }
  342. func mean(values []int64) float64 {
  343. if 0 == len(values) {
  344. return 0.0
  345. }
  346. var sum int64
  347. for _, v := range values {
  348. sum += v
  349. }
  350. return float64(sum) / float64(len(values))
  351. }
  352. func min(values []int64) int64 {
  353. if 0 == len(values) {
  354. return 0
  355. }
  356. var min int64 = math.MaxInt64
  357. for _, v := range values {
  358. if min > v {
  359. min = v
  360. }
  361. }
  362. return min
  363. }
  364. func percentiles(values int64Slice, ps []float64) []float64 {
  365. scores := make([]float64, len(ps))
  366. size := len(values)
  367. if size > 0 {
  368. sort.Sort(values)
  369. for i, p := range ps {
  370. pos := p * float64(size+1)
  371. if pos < 1.0 {
  372. scores[i] = float64(values[0])
  373. } else if pos >= float64(size) {
  374. scores[i] = float64(values[size-1])
  375. } else {
  376. lower := float64(values[int(pos)-1])
  377. upper := float64(values[int(pos)])
  378. scores[i] = lower + (pos-math.Floor(pos))*(upper-lower)
  379. }
  380. }
  381. }
  382. return scores
  383. }
  384. func variance(values []int64) float64 {
  385. m := mean(values)
  386. var sum float64
  387. for _, v := range values {
  388. d := float64(v) - m
  389. sum += d * d
  390. }
  391. return sum / float64(len(values))
  392. }