sample.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. // includes code from
  2. // https://raw.githubusercontent.com/rcrowley/go-metrics/master/sample.go
  3. // Copyright 2012 Richard Crowley. All rights reserved.
  4. package metrics
  5. import (
  6. "math"
  7. "math/rand"
  8. "sort"
  9. "sync"
  10. "time"
  11. )
  12. const rescaleThreshold = time.Hour
  13. // Samples maintain a statistically-significant selection of values from
  14. // a stream.
  15. type Sample interface {
  16. Clear()
  17. Count() int64
  18. Max() int64
  19. Mean() float64
  20. Min() int64
  21. Percentile(float64) float64
  22. Percentiles([]float64) []float64
  23. Size() int
  24. Snapshot() Sample
  25. StdDev() float64
  26. Sum() int64
  27. Update(int64)
  28. Values() []int64
  29. Variance() float64
  30. }
  31. // ExpDecaySample is an exponentially-decaying sample using a forward-decaying
  32. // priority reservoir. See Cormode et al's "Forward Decay: A Practical Time
  33. // Decay Model for Streaming Systems".
  34. //
  35. // <http://www.research.att.com/people/Cormode_Graham/library/publications/CormodeShkapenyukSrivastavaXu09.pdf>
  36. type ExpDecaySample struct {
  37. alpha float64
  38. count int64
  39. mutex sync.Mutex
  40. reservoirSize int
  41. t0, t1 time.Time
  42. values *expDecaySampleHeap
  43. }
  44. // NewExpDecaySample constructs a new exponentially-decaying sample with the
  45. // given reservoir size and alpha.
  46. func NewExpDecaySample(reservoirSize int, alpha float64) Sample {
  47. s := &ExpDecaySample{
  48. alpha: alpha,
  49. reservoirSize: reservoirSize,
  50. t0: time.Now(),
  51. values: newExpDecaySampleHeap(reservoirSize),
  52. }
  53. s.t1 = s.t0.Add(rescaleThreshold)
  54. return s
  55. }
  56. // Clear clears all samples.
  57. func (s *ExpDecaySample) Clear() {
  58. s.mutex.Lock()
  59. defer s.mutex.Unlock()
  60. s.count = 0
  61. s.t0 = time.Now()
  62. s.t1 = s.t0.Add(rescaleThreshold)
  63. s.values.Clear()
  64. }
  65. // Count returns the number of samples recorded, which may exceed the
  66. // reservoir size.
  67. func (s *ExpDecaySample) Count() int64 {
  68. s.mutex.Lock()
  69. defer s.mutex.Unlock()
  70. return s.count
  71. }
  72. // Max returns the maximum value in the sample, which may not be the maximum
  73. // value ever to be part of the sample.
  74. func (s *ExpDecaySample) Max() int64 {
  75. return SampleMax(s.Values())
  76. }
  77. // Mean returns the mean of the values in the sample.
  78. func (s *ExpDecaySample) Mean() float64 {
  79. return SampleMean(s.Values())
  80. }
  81. // Min returns the minimum value in the sample, which may not be the minimum
  82. // value ever to be part of the sample.
  83. func (s *ExpDecaySample) Min() int64 {
  84. return SampleMin(s.Values())
  85. }
  86. // Percentile returns an arbitrary percentile of values in the sample.
  87. func (s *ExpDecaySample) Percentile(p float64) float64 {
  88. return SamplePercentile(s.Values(), p)
  89. }
  90. // Percentiles returns a slice of arbitrary percentiles of values in the
  91. // sample.
  92. func (s *ExpDecaySample) Percentiles(ps []float64) []float64 {
  93. return SamplePercentiles(s.Values(), ps)
  94. }
  95. // Size returns the size of the sample, which is at most the reservoir size.
  96. func (s *ExpDecaySample) Size() int {
  97. s.mutex.Lock()
  98. defer s.mutex.Unlock()
  99. return s.values.Size()
  100. }
  101. // Snapshot returns a read-only copy of the sample.
  102. func (s *ExpDecaySample) Snapshot() Sample {
  103. s.mutex.Lock()
  104. defer s.mutex.Unlock()
  105. vals := s.values.Values()
  106. values := make([]int64, len(vals))
  107. for i, v := range vals {
  108. values[i] = v.v
  109. }
  110. return &SampleSnapshot{
  111. count: s.count,
  112. values: values,
  113. }
  114. }
  115. // StdDev returns the standard deviation of the values in the sample.
  116. func (s *ExpDecaySample) StdDev() float64 {
  117. return SampleStdDev(s.Values())
  118. }
  119. // Sum returns the sum of the values in the sample.
  120. func (s *ExpDecaySample) Sum() int64 {
  121. return SampleSum(s.Values())
  122. }
  123. // Update samples a new value.
  124. func (s *ExpDecaySample) Update(v int64) {
  125. s.update(time.Now(), v)
  126. }
  127. // Values returns a copy of the values in the sample.
  128. func (s *ExpDecaySample) Values() []int64 {
  129. s.mutex.Lock()
  130. defer s.mutex.Unlock()
  131. vals := s.values.Values()
  132. values := make([]int64, len(vals))
  133. for i, v := range vals {
  134. values[i] = v.v
  135. }
  136. return values
  137. }
  138. // Variance returns the variance of the values in the sample.
  139. func (s *ExpDecaySample) Variance() float64 {
  140. return SampleVariance(s.Values())
  141. }
  142. // update samples a new value at a particular timestamp. This is a method all
  143. // its own to facilitate testing.
  144. func (s *ExpDecaySample) update(t time.Time, v int64) {
  145. s.mutex.Lock()
  146. defer s.mutex.Unlock()
  147. s.count++
  148. if s.values.Size() == s.reservoirSize {
  149. s.values.Pop()
  150. }
  151. s.values.Push(expDecaySample{
  152. k: math.Exp(t.Sub(s.t0).Seconds()*s.alpha) / rand.Float64(),
  153. v: v,
  154. })
  155. if t.After(s.t1) {
  156. values := s.values.Values()
  157. t0 := s.t0
  158. s.values.Clear()
  159. s.t0 = t
  160. s.t1 = s.t0.Add(rescaleThreshold)
  161. for _, v := range values {
  162. v.k = v.k * math.Exp(-s.alpha*s.t0.Sub(t0).Seconds())
  163. s.values.Push(v)
  164. }
  165. }
  166. }
  167. // NilSample is a no-op Sample.
  168. type NilSample struct{}
  169. // Clear is a no-op.
  170. func (NilSample) Clear() {}
  171. // Count is a no-op.
  172. func (NilSample) Count() int64 { return 0 }
  173. // Max is a no-op.
  174. func (NilSample) Max() int64 { return 0 }
  175. // Mean is a no-op.
  176. func (NilSample) Mean() float64 { return 0.0 }
  177. // Min is a no-op.
  178. func (NilSample) Min() int64 { return 0 }
  179. // Percentile is a no-op.
  180. func (NilSample) Percentile(p float64) float64 { return 0.0 }
  181. // Percentiles is a no-op.
  182. func (NilSample) Percentiles(ps []float64) []float64 {
  183. return make([]float64, len(ps))
  184. }
  185. // Size is a no-op.
  186. func (NilSample) Size() int { return 0 }
  187. // Sample is a no-op.
  188. func (NilSample) Snapshot() Sample { return NilSample{} }
  189. // StdDev is a no-op.
  190. func (NilSample) StdDev() float64 { return 0.0 }
  191. // Sum is a no-op.
  192. func (NilSample) Sum() int64 { return 0 }
  193. // Update is a no-op.
  194. func (NilSample) Update(v int64) {}
  195. // Values is a no-op.
  196. func (NilSample) Values() []int64 { return []int64{} }
  197. // Variance is a no-op.
  198. func (NilSample) Variance() float64 { return 0.0 }
  199. // SampleMax returns the maximum value of the slice of int64.
  200. func SampleMax(values []int64) int64 {
  201. if 0 == len(values) {
  202. return 0
  203. }
  204. var max int64 = math.MinInt64
  205. for _, v := range values {
  206. if max < v {
  207. max = v
  208. }
  209. }
  210. return max
  211. }
  212. // SampleMean returns the mean value of the slice of int64.
  213. func SampleMean(values []int64) float64 {
  214. if 0 == len(values) {
  215. return 0.0
  216. }
  217. return float64(SampleSum(values)) / float64(len(values))
  218. }
  219. // SampleMin returns the minimum value of the slice of int64.
  220. func SampleMin(values []int64) int64 {
  221. if 0 == len(values) {
  222. return 0
  223. }
  224. var min int64 = math.MaxInt64
  225. for _, v := range values {
  226. if min > v {
  227. min = v
  228. }
  229. }
  230. return min
  231. }
  232. // SamplePercentiles returns an arbitrary percentile of the slice of int64.
  233. func SamplePercentile(values int64Slice, p float64) float64 {
  234. return SamplePercentiles(values, []float64{p})[0]
  235. }
  236. // SamplePercentiles returns a slice of arbitrary percentiles of the slice of
  237. // int64.
  238. func SamplePercentiles(values int64Slice, ps []float64) []float64 {
  239. scores := make([]float64, len(ps))
  240. size := len(values)
  241. if size > 0 {
  242. sort.Sort(values)
  243. for i, p := range ps {
  244. pos := p * float64(size+1)
  245. if pos < 1.0 {
  246. scores[i] = float64(values[0])
  247. } else if pos >= float64(size) {
  248. scores[i] = float64(values[size-1])
  249. } else {
  250. lower := float64(values[int(pos)-1])
  251. upper := float64(values[int(pos)])
  252. scores[i] = lower + (pos-math.Floor(pos))*(upper-lower)
  253. }
  254. }
  255. }
  256. return scores
  257. }
  258. // SampleSnapshot is a read-only copy of another Sample.
  259. type SampleSnapshot struct {
  260. count int64
  261. values []int64
  262. }
  263. // Clear panics.
  264. func (*SampleSnapshot) Clear() {
  265. panic("Clear called on a SampleSnapshot")
  266. }
  267. // Count returns the count of inputs at the time the snapshot was taken.
  268. func (s *SampleSnapshot) Count() int64 { return s.count }
  269. // Max returns the maximal value at the time the snapshot was taken.
  270. func (s *SampleSnapshot) Max() int64 { return SampleMax(s.values) }
  271. // Mean returns the mean value at the time the snapshot was taken.
  272. func (s *SampleSnapshot) Mean() float64 { return SampleMean(s.values) }
  273. // Min returns the minimal value at the time the snapshot was taken.
  274. func (s *SampleSnapshot) Min() int64 { return SampleMin(s.values) }
  275. // Percentile returns an arbitrary percentile of values at the time the
  276. // snapshot was taken.
  277. func (s *SampleSnapshot) Percentile(p float64) float64 {
  278. return SamplePercentile(s.values, p)
  279. }
  280. // Percentiles returns a slice of arbitrary percentiles of values at the time
  281. // the snapshot was taken.
  282. func (s *SampleSnapshot) Percentiles(ps []float64) []float64 {
  283. return SamplePercentiles(s.values, ps)
  284. }
  285. // Size returns the size of the sample at the time the snapshot was taken.
  286. func (s *SampleSnapshot) Size() int { return len(s.values) }
  287. // Snapshot returns the snapshot.
  288. func (s *SampleSnapshot) Snapshot() Sample { return s }
  289. // StdDev returns the standard deviation of values at the time the snapshot was
  290. // taken.
  291. func (s *SampleSnapshot) StdDev() float64 { return SampleStdDev(s.values) }
  292. // Sum returns the sum of values at the time the snapshot was taken.
  293. func (s *SampleSnapshot) Sum() int64 { return SampleSum(s.values) }
  294. // Update panics.
  295. func (*SampleSnapshot) Update(int64) {
  296. panic("Update called on a SampleSnapshot")
  297. }
  298. // Values returns a copy of the values in the sample.
  299. func (s *SampleSnapshot) Values() []int64 {
  300. values := make([]int64, len(s.values))
  301. copy(values, s.values)
  302. return values
  303. }
  304. // Variance returns the variance of values at the time the snapshot was taken.
  305. func (s *SampleSnapshot) Variance() float64 { return SampleVariance(s.values) }
  306. // SampleStdDev returns the standard deviation of the slice of int64.
  307. func SampleStdDev(values []int64) float64 {
  308. return math.Sqrt(SampleVariance(values))
  309. }
  310. // SampleSum returns the sum of the slice of int64.
  311. func SampleSum(values []int64) int64 {
  312. var sum int64
  313. for _, v := range values {
  314. sum += v
  315. }
  316. return sum
  317. }
  318. // SampleVariance returns the variance of the slice of int64.
  319. func SampleVariance(values []int64) float64 {
  320. if 0 == len(values) {
  321. return 0.0
  322. }
  323. m := SampleMean(values)
  324. var sum float64
  325. for _, v := range values {
  326. d := float64(v) - m
  327. sum += d * d
  328. }
  329. return sum / float64(len(values))
  330. }
  331. // A uniform sample using Vitter's Algorithm R.
  332. //
  333. // <http://www.cs.umd.edu/~samir/498/vitter.pdf>
  334. type UniformSample struct {
  335. count int64
  336. mutex sync.Mutex
  337. reservoirSize int
  338. values []int64
  339. }
  340. // NewUniformSample constructs a new uniform sample with the given reservoir
  341. // size.
  342. func NewUniformSample(reservoirSize int) Sample {
  343. return &UniformSample{
  344. reservoirSize: reservoirSize,
  345. values: make([]int64, 0, reservoirSize),
  346. }
  347. }
  348. // Clear clears all samples.
  349. func (s *UniformSample) Clear() {
  350. s.mutex.Lock()
  351. defer s.mutex.Unlock()
  352. s.count = 0
  353. s.values = make([]int64, 0, s.reservoirSize)
  354. }
  355. // Count returns the number of samples recorded, which may exceed the
  356. // reservoir size.
  357. func (s *UniformSample) Count() int64 {
  358. s.mutex.Lock()
  359. defer s.mutex.Unlock()
  360. return s.count
  361. }
  362. // Max returns the maximum value in the sample, which may not be the maximum
  363. // value ever to be part of the sample.
  364. func (s *UniformSample) Max() int64 {
  365. s.mutex.Lock()
  366. defer s.mutex.Unlock()
  367. return SampleMax(s.values)
  368. }
  369. // Mean returns the mean of the values in the sample.
  370. func (s *UniformSample) Mean() float64 {
  371. s.mutex.Lock()
  372. defer s.mutex.Unlock()
  373. return SampleMean(s.values)
  374. }
  375. // Min returns the minimum value in the sample, which may not be the minimum
  376. // value ever to be part of the sample.
  377. func (s *UniformSample) Min() int64 {
  378. s.mutex.Lock()
  379. defer s.mutex.Unlock()
  380. return SampleMin(s.values)
  381. }
  382. // Percentile returns an arbitrary percentile of values in the sample.
  383. func (s *UniformSample) Percentile(p float64) float64 {
  384. s.mutex.Lock()
  385. defer s.mutex.Unlock()
  386. return SamplePercentile(s.values, p)
  387. }
  388. // Percentiles returns a slice of arbitrary percentiles of values in the
  389. // sample.
  390. func (s *UniformSample) Percentiles(ps []float64) []float64 {
  391. s.mutex.Lock()
  392. defer s.mutex.Unlock()
  393. return SamplePercentiles(s.values, ps)
  394. }
  395. // Size returns the size of the sample, which is at most the reservoir size.
  396. func (s *UniformSample) Size() int {
  397. s.mutex.Lock()
  398. defer s.mutex.Unlock()
  399. return len(s.values)
  400. }
  401. // Snapshot returns a read-only copy of the sample.
  402. func (s *UniformSample) Snapshot() Sample {
  403. s.mutex.Lock()
  404. defer s.mutex.Unlock()
  405. values := make([]int64, len(s.values))
  406. copy(values, s.values)
  407. return &SampleSnapshot{
  408. count: s.count,
  409. values: values,
  410. }
  411. }
  412. // StdDev returns the standard deviation of the values in the sample.
  413. func (s *UniformSample) StdDev() float64 {
  414. s.mutex.Lock()
  415. defer s.mutex.Unlock()
  416. return SampleStdDev(s.values)
  417. }
  418. // Sum returns the sum of the values in the sample.
  419. func (s *UniformSample) Sum() int64 {
  420. s.mutex.Lock()
  421. defer s.mutex.Unlock()
  422. return SampleSum(s.values)
  423. }
  424. // Update samples a new value.
  425. func (s *UniformSample) Update(v int64) {
  426. s.mutex.Lock()
  427. defer s.mutex.Unlock()
  428. s.count++
  429. if len(s.values) < s.reservoirSize {
  430. s.values = append(s.values, v)
  431. } else {
  432. r := rand.Int63n(s.count)
  433. if r < int64(len(s.values)) {
  434. s.values[int(r)] = v
  435. }
  436. }
  437. }
  438. // Values returns a copy of the values in the sample.
  439. func (s *UniformSample) Values() []int64 {
  440. s.mutex.Lock()
  441. defer s.mutex.Unlock()
  442. values := make([]int64, len(s.values))
  443. copy(values, s.values)
  444. return values
  445. }
  446. // Variance returns the variance of the values in the sample.
  447. func (s *UniformSample) Variance() float64 {
  448. s.mutex.Lock()
  449. defer s.mutex.Unlock()
  450. return SampleVariance(s.values)
  451. }
  452. // expDecaySample represents an individual sample in a heap.
  453. type expDecaySample struct {
  454. k float64
  455. v int64
  456. }
  457. func newExpDecaySampleHeap(reservoirSize int) *expDecaySampleHeap {
  458. return &expDecaySampleHeap{make([]expDecaySample, 0, reservoirSize)}
  459. }
  460. // expDecaySampleHeap is a min-heap of expDecaySamples.
  461. // The internal implementation is copied from the standard library's container/heap
  462. type expDecaySampleHeap struct {
  463. s []expDecaySample
  464. }
  465. func (h *expDecaySampleHeap) Clear() {
  466. h.s = h.s[:0]
  467. }
  468. func (h *expDecaySampleHeap) Push(s expDecaySample) {
  469. n := len(h.s)
  470. h.s = h.s[0 : n+1]
  471. h.s[n] = s
  472. h.up(n)
  473. }
  474. func (h *expDecaySampleHeap) Pop() expDecaySample {
  475. n := len(h.s) - 1
  476. h.s[0], h.s[n] = h.s[n], h.s[0]
  477. h.down(0, n)
  478. n = len(h.s)
  479. s := h.s[n-1]
  480. h.s = h.s[0 : n-1]
  481. return s
  482. }
  483. func (h *expDecaySampleHeap) Size() int {
  484. return len(h.s)
  485. }
  486. func (h *expDecaySampleHeap) Values() []expDecaySample {
  487. return h.s
  488. }
  489. func (h *expDecaySampleHeap) up(j int) {
  490. for {
  491. i := (j - 1) / 2 // parent
  492. if i == j || !(h.s[j].k < h.s[i].k) {
  493. break
  494. }
  495. h.s[i], h.s[j] = h.s[j], h.s[i]
  496. j = i
  497. }
  498. }
  499. func (h *expDecaySampleHeap) down(i, n int) {
  500. for {
  501. j1 := 2*i + 1
  502. if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
  503. break
  504. }
  505. j := j1 // left child
  506. if j2 := j1 + 1; j2 < n && !(h.s[j1].k < h.s[j2].k) {
  507. j = j2 // = 2*i + 2 // right child
  508. }
  509. if !(h.s[j].k < h.s[i].k) {
  510. break
  511. }
  512. h.s[i], h.s[j] = h.s[j], h.s[i]
  513. i = j
  514. }
  515. }
  516. type int64Slice []int64
  517. func (p int64Slice) Len() int { return len(p) }
  518. func (p int64Slice) Less(i, j int) bool { return p[i] < p[j] }
  519. func (p int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }