sample.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 = 1e9 * 60 * 60
  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.mutex.Lock()
  124. defer s.mutex.Unlock()
  125. s.count++
  126. if len(s.values) == s.reservoirSize {
  127. heap.Pop(&s.values)
  128. }
  129. t := time.Now()
  130. heap.Push(&s.values, expDecaySample{
  131. k: math.Exp(t.Sub(s.t0).Seconds()*s.alpha) / rand.Float64(),
  132. v: v,
  133. })
  134. if t.After(s.t1) {
  135. values := s.values
  136. t0 := s.t0
  137. s.values = make(expDecaySampleHeap, 0, s.reservoirSize)
  138. s.t0 = t
  139. s.t1 = s.t0.Add(rescaleThreshold)
  140. for _, v := range values {
  141. v.k = v.k * math.Exp(-s.alpha*float64(s.t0.Sub(t0)))
  142. heap.Push(&s.values, v)
  143. }
  144. }
  145. }
  146. // Values returns a copy of the values in the sample.
  147. func (s *ExpDecaySample) Values() []int64 {
  148. s.mutex.Lock()
  149. defer s.mutex.Unlock()
  150. values := make([]int64, len(s.values))
  151. for i, v := range s.values {
  152. values[i] = v.v
  153. }
  154. return values
  155. }
  156. // Variance returns the variance of the sample.
  157. func (s *ExpDecaySample) Variance() float64 {
  158. return variance(s.Values())
  159. }
  160. // No-op Sample.
  161. type NilSample struct{}
  162. // No-op.
  163. func (NilSample) Clear() {}
  164. // No-op.
  165. func (NilSample) Count() int64 { return 0 }
  166. // No-op.
  167. func (NilSample) Dup() Sample { return NilSample{} }
  168. // No-op.
  169. func (NilSample) Max() int64 { return 0 }
  170. // No-op.
  171. func (NilSample) Mean() float64 { return 0.0 }
  172. // No-op.
  173. func (NilSample) Min() int64 { return 0 }
  174. // No-op.
  175. func (NilSample) Percentile(p float64) float64 { return 0.0 }
  176. // No-op.
  177. func (NilSample) Percentiles(ps []float64) []float64 {
  178. return make([]float64, len(ps))
  179. }
  180. // No-op.
  181. func (NilSample) Size() int { return 0 }
  182. // No-op.
  183. func (NilSample) StdDev() float64 { return 0.0 }
  184. // No-op.
  185. func (NilSample) Update(v int64) {}
  186. // No-op.
  187. func (NilSample) Values() []int64 { return []int64{} }
  188. // No-op.
  189. func (NilSample) Variance() float64 { return 0.0 }
  190. // A uniform sample using Vitter's Algorithm R.
  191. //
  192. // <http://www.cs.umd.edu/~samir/498/vitter.pdf>
  193. type UniformSample struct {
  194. count int64
  195. mutex sync.Mutex
  196. reservoirSize int
  197. values []int64
  198. }
  199. // Create a new uniform sample with the given reservoir size.
  200. func NewUniformSample(reservoirSize int) Sample {
  201. if UseNilMetrics {
  202. return NilSample{}
  203. }
  204. return &UniformSample{reservoirSize: reservoirSize}
  205. }
  206. // Clear all samples.
  207. func (s *UniformSample) Clear() {
  208. s.mutex.Lock()
  209. defer s.mutex.Unlock()
  210. s.count = 0
  211. s.values = make([]int64, 0, s.reservoirSize)
  212. }
  213. // Count returns the number of samples recorded, which may exceed the
  214. // reservoir size.
  215. func (s *UniformSample) Count() int64 {
  216. return atomic.LoadInt64(&s.count)
  217. }
  218. // Dup returns a copy of the sample.
  219. func (s *UniformSample) Dup() Sample {
  220. s.mutex.Lock()
  221. defer s.mutex.Unlock()
  222. values := make([]int64, len(s.values))
  223. copy(values, s.values)
  224. return &UniformSample{
  225. count: s.count,
  226. reservoirSize: s.reservoirSize,
  227. values: values,
  228. }
  229. }
  230. // Max returns the maximum value in the sample, which may not be the maximum
  231. // value ever to be part of the sample.
  232. func (s *UniformSample) Max() int64 {
  233. s.mutex.Lock()
  234. defer s.mutex.Unlock()
  235. return max(s.values)
  236. }
  237. // Return the mean of all values seen since the histogram was last cleared.
  238. func (s *UniformSample) Mean() float64 {
  239. s.mutex.Lock()
  240. defer s.mutex.Unlock()
  241. return mean(s.values)
  242. }
  243. // Min returns the minimum value in the sample, which may not be the minimum
  244. // value ever to be part of the sample.
  245. func (s *UniformSample) Min() int64 {
  246. s.mutex.Lock()
  247. defer s.mutex.Unlock()
  248. return min(s.values)
  249. }
  250. // Percentile returns an arbitrary percentile of sampled values.
  251. func (s *UniformSample) Percentile(p float64) float64 {
  252. return s.Percentiles([]float64{p})[0]
  253. }
  254. // Percentiles returns a slice of arbitrary percentiles of sampled values.
  255. func (s *UniformSample) Percentiles(ps []float64) []float64 {
  256. s.mutex.Lock()
  257. defer s.mutex.Unlock()
  258. return percentiles(s.values, ps)
  259. }
  260. // Return the size of the sample, which is at most the reservoir size.
  261. func (s *UniformSample) Size() int {
  262. s.mutex.Lock()
  263. defer s.mutex.Unlock()
  264. return len(s.values)
  265. }
  266. // StdDev returns the standard deviation of the sample.
  267. func (s *UniformSample) StdDev() float64 {
  268. return math.Sqrt(s.Variance())
  269. }
  270. // Update the sample with a new value.
  271. func (s *UniformSample) Update(v int64) {
  272. s.mutex.Lock()
  273. defer s.mutex.Unlock()
  274. s.count++
  275. if len(s.values) < s.reservoirSize {
  276. s.values = append(s.values, v)
  277. } else {
  278. s.values[rand.Intn(s.reservoirSize)] = v
  279. }
  280. }
  281. // Return all the values in the sample.
  282. func (s *UniformSample) Values() []int64 {
  283. s.mutex.Lock()
  284. defer s.mutex.Unlock()
  285. values := make([]int64, len(s.values))
  286. copy(values, s.values)
  287. return values
  288. }
  289. // Variance returns the variance of the sample.
  290. func (s *UniformSample) Variance() float64 {
  291. s.mutex.Lock()
  292. defer s.mutex.Unlock()
  293. return variance(s.values)
  294. }
  295. // expDecaySample represents an individual sample in a heap.
  296. type expDecaySample struct {
  297. k float64
  298. v int64
  299. }
  300. // expDecaySampleHeap is a min-heap of expDecaySamples.
  301. type expDecaySampleHeap []expDecaySample
  302. func (q expDecaySampleHeap) Len() int {
  303. return len(q)
  304. }
  305. func (q expDecaySampleHeap) Less(i, j int) bool {
  306. return q[i].k < q[j].k
  307. }
  308. func (q *expDecaySampleHeap) Pop() interface{} {
  309. q_ := *q
  310. n := len(q_)
  311. i := q_[n-1]
  312. q_ = q_[0 : n-1]
  313. *q = q_
  314. return i
  315. }
  316. func (q *expDecaySampleHeap) Push(x interface{}) {
  317. q_ := *q
  318. n := len(q_)
  319. q_ = q_[0 : n+1]
  320. q_[n] = x.(expDecaySample)
  321. *q = q_
  322. }
  323. func (q expDecaySampleHeap) Swap(i, j int) {
  324. q[i], q[j] = q[j], q[i]
  325. }
  326. func max(values []int64) int64 {
  327. if 0 == len(values) {
  328. return 0
  329. }
  330. var max int64 = math.MinInt64
  331. for _, v := range values {
  332. if max < v {
  333. max = v
  334. }
  335. }
  336. return max
  337. }
  338. func mean(values []int64) float64 {
  339. if 0 == len(values) {
  340. return 0.0
  341. }
  342. var sum int64
  343. for _, v := range values {
  344. sum += v
  345. }
  346. return float64(sum) / float64(len(values))
  347. }
  348. func min(values []int64) int64 {
  349. if 0 == len(values) {
  350. return 0
  351. }
  352. var min int64 = math.MaxInt64
  353. for _, v := range values {
  354. if min > v {
  355. min = v
  356. }
  357. }
  358. return min
  359. }
  360. func percentiles(values int64Slice, ps []float64) []float64 {
  361. scores := make([]float64, len(ps))
  362. size := len(values)
  363. if size > 0 {
  364. sort.Sort(values)
  365. for i, p := range ps {
  366. pos := p * float64(size+1)
  367. if pos < 1.0 {
  368. scores[i] = float64(values[0])
  369. } else if pos >= float64(size) {
  370. scores[i] = float64(values[size-1])
  371. } else {
  372. lower := float64(values[int(pos)-1])
  373. upper := float64(values[int(pos)])
  374. scores[i] = lower + (pos-math.Floor(pos))*(upper-lower)
  375. }
  376. }
  377. }
  378. return scores
  379. }
  380. func variance(values []int64) float64 {
  381. m := mean(values)
  382. var sum float64
  383. for _, v := range values {
  384. d := float64(v) - m
  385. sum += d * d
  386. }
  387. return sum / float64(len(values))
  388. }