当前位置:   article > 正文

golang 实现时间滑动窗口_golang 滑动窗口

golang 滑动窗口

一 概念

固定窗口就像是滑动窗口的一个特例,固定窗口是大小固定且不能随着时间而变化的。

滑动时间窗口就是把一段时间片分为多个样本窗口,可以通过更细粒度对数据进行统计。然后计算对应的时间落在那个窗口上,来对数据统计;滑动时间窗口,随着时间流失,最开始的样本窗口将会失效,同时会生成新的样本窗口。

例如 我们将1s划分为4个样本窗口,每个样本窗口对应250ms。

二 go-zero中的滑动窗口实现

1.Bucket 样本窗口

Bucket用于记录每个样本窗口的值

  1. // Bucket defines the bucket that holds sum and num of additions.
  2. type Bucket struct {
  3. Sum float64 //样本窗口的值
  4. Count int64 //样本窗口被add的次数
  5. }
  6. func (b *Bucket) add(v float64) {
  7. b.Sum += v
  8. b.Count++
  9. }
  10. //重置样本窗口,样本窗口过期时
  11. func (b *Bucket) reset() {
  12. b.Sum = 0
  13. b.Count = 0
  14. }


2. window 滑动窗口

  1. type window struct {
  2. buckets []*Bucket //样本窗口
  3. size int //样本窗口个数
  4. }
  5. func newWindow(size int) *window {
  6. buckets := make([]*Bucket, size)
  7. for i := 0; i < size; i++ {
  8. buckets[i] = new(Bucket)
  9. }
  10. return &window{
  11. buckets: buckets,
  12. size: size,
  13. }
  14. }
  15. func (w *window) add(offset int, v float64) {
  16. w.buckets[offset%w.size].add(v)
  17. }
  18. func (w *window) reduce(start, count int, fn func(b *Bucket)) {
  19. for i := 0; i < count; i++ {
  20. fn(w.buckets[(start+i)%w.size])
  21. }
  22. }
  23. func (w *window) resetBucket(offset int) {
  24. w.buckets[offset%w.size].reset()
  25. }

3. RollingWindow窗口

bucket和window的实现都很简单,逻辑很好理解。

RollingWindow相对复杂一些。

当add值时需要如下操作:

  1. 计算已经过期的bucket(样本窗口),将已经过期的bucket重置。
  2. 计算offset,当前add操作应当记录到哪个bucket中。
  1. type (
  2. // RollingWindowOption let callers customize the RollingWindow.
  3. RollingWindowOption func(rollingWindow *RollingWindow)
  4. // RollingWindow defines a rolling window to calculate the events in buckets with time interval.
  5. RollingWindow struct {
  6. lock sync.RWMutex
  7. size int
  8. win *window
  9. interval time.Duration
  10. offset int
  11. ignoreCurrent bool
  12. lastTime time.Duration // start time of the last bucket
  13. }
  14. )
  15. // NewRollingWindow returns a RollingWindow that with size buckets and time interval,
  16. // use opts to customize the RollingWindow.
  17. func NewRollingWindow(size int, interval time.Duration, opts ...RollingWindowOption) *RollingWindow {
  18. if size < 1 {
  19. panic("size must be greater than 0")
  20. }
  21. w := &RollingWindow{
  22. size: size,
  23. win: newWindow(size),
  24. interval: interval,
  25. lastTime: timex.Now(),
  26. }
  27. for _, opt := range opts {
  28. opt(w)
  29. }
  30. return w
  31. }
  32. // Add adds value to current bucket.
  33. func (rw *RollingWindow) Add(v float64) {
  34. rw.lock.Lock()
  35. defer rw.lock.Unlock()
  36. rw.updateOffset()
  37. rw.win.add(rw.offset, v)
  38. }
  39. // Reduce runs fn on all buckets, ignore current bucket if ignoreCurrent was set.
  40. func (rw *RollingWindow) Reduce(fn func(b *Bucket)) {
  41. rw.lock.RLock()
  42. defer rw.lock.RUnlock()
  43. var diff int
  44. //获取跨度,并计算还有几个bucket还在窗口期内
  45. span := rw.span()
  46. // ignore current bucket, because of partial data
  47. if span == 0 && rw.ignoreCurrent {
  48. diff = rw.size - 1
  49. } else {
  50. diff = rw.size - span
  51. }
  52. if diff > 0 {
  53. offset := (rw.offset + span + 1) % rw.size
  54. rw.win.reduce(offset, diff, fn)
  55. }
  56. }
  57. //距离上次add操作跨度,
  58. //例如 lastTime = 1s, 当前时间1777ms。样本窗口时间250ms,那么跨度为3个样本窗口
  59. func (rw *RollingWindow) span() int {
  60. offset := int(timex.Since(rw.lastTime) / rw.interval)
  61. if 0 <= offset && offset < rw.size {
  62. return offset
  63. }
  64. return rw.size
  65. }
  66. //g
  67. func (rw *RollingWindow) updateOffset() {
  68. span := rw.span()
  69. if span <= 0 {
  70. return
  71. }
  72. offset := rw.offset
  73. // reset expired buckets ,重置已经超时的bucket
  74. for i := 0; i < span; i++ {
  75. rw.win.resetBucket((offset + i + 1) % rw.size)
  76. }
  77. rw.offset = (offset + span) % rw.size
  78. now := timex.Now()
  79. //和样本窗口时间对齐
  80. rw.lastTime = now - (now-rw.lastTime)%rw.interval
  81. }


三 使用

  1. //1.新建一个4样本窗口,每个样本窗口250ms
  2. rollingWindow:= NewRollingWindow(4, time.Millisecond*250,IgnoreCurrentBucket())
  3. //2.add
  4. rollingWindow.Add(1)
  5. rollingWindow.Add(2)
  6. time.Sleep(time.Millisecond*250)
  7. rollingWindow.Add(3)
  8. rollingWindow.Add(4)
  9. //3.获取滑动窗口的值
  10. var Sum float64
  11. var total int64
  12. rollingWindow.Reduce(func(b *collection.Bucket) {
  13. Sum += int64(b.Sum)
  14. total += b.Count
  15. })

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/468521
推荐阅读
相关标签
  

闽ICP备14008679号