golang 實(shí)現(xiàn)時(shí)間滑動(dòng)窗口的示例代碼
一 概念
固定窗口就像是滑動(dòng)窗口的一個(gè)特例,固定窗口是大小固定且不能隨著時(shí)間而變化的。
滑動(dòng)時(shí)間窗口就是把一段時(shí)間片分為多個(gè)樣本窗口,可以通過(guò)更細(xì)粒度對(duì)數(shù)據(jù)進(jìn)行統(tǒng)計(jì)。然后計(jì)算對(duì)應(yīng)的時(shí)間落在那個(gè)窗口上,來(lái)對(duì)數(shù)據(jù)統(tǒng)計(jì);滑動(dòng)時(shí)間窗口,隨著時(shí)間流失,最開(kāi)始的樣本窗口將會(huì)失效,同時(shí)會(huì)生成新的樣本窗口。
例如 我們將1s劃分為4個(gè)樣本窗口,每個(gè)樣本窗口對(duì)應(yīng)250ms。

二 go-zero中的滑動(dòng)窗口實(shí)現(xiàn)
1.Bucket 樣本窗口
Bucket用于記錄每個(gè)樣本窗口的值
// Bucket defines the bucket that holds sum and num of additions.
type Bucket struct {
Sum float64 //樣本窗口的值
Count int64 //樣本窗口被add的次數(shù)
}
func (b *Bucket) add(v float64) {
b.Sum += v
b.Count++
}
//重置樣本窗口,樣本窗口過(guò)期時(shí)
func (b *Bucket) reset() {
b.Sum = 0
b.Count = 0
}2. window 滑動(dòng)窗口
type window struct {
buckets []*Bucket //樣本窗口
size int //樣本窗口個(gè)數(shù)
}
func newWindow(size int) *window {
buckets := make([]*Bucket, size)
for i := 0; i < size; i++ {
buckets[i] = new(Bucket)
}
return &window{
buckets: buckets,
size: size,
}
}
func (w *window) add(offset int, v float64) {
w.buckets[offset%w.size].add(v)
}
func (w *window) reduce(start, count int, fn func(b *Bucket)) {
for i := 0; i < count; i++ {
fn(w.buckets[(start+i)%w.size])
}
}
func (w *window) resetBucket(offset int) {
w.buckets[offset%w.size].reset()
}3. RollingWindow窗口
bucket和window的實(shí)現(xiàn)都很簡(jiǎn)單,邏輯很好理解。
RollingWindow相對(duì)復(fù)雜一些。
當(dāng)add值時(shí)需要如下操作:
- 計(jì)算已經(jīng)過(guò)期的bucket(樣本窗口),將已經(jīng)過(guò)期的bucket重置。
- 計(jì)算offset,當(dāng)前add操作應(yīng)當(dāng)記錄到哪個(gè)bucket中。
type (
// RollingWindowOption let callers customize the RollingWindow.
RollingWindowOption func(rollingWindow *RollingWindow)
// RollingWindow defines a rolling window to calculate the events in buckets with time interval.
RollingWindow struct {
lock sync.RWMutex
size int
win *window
interval time.Duration
offset int
ignoreCurrent bool
lastTime time.Duration // start time of the last bucket
}
)
// NewRollingWindow returns a RollingWindow that with size buckets and time interval,
// use opts to customize the RollingWindow.
func NewRollingWindow(size int, interval time.Duration, opts ...RollingWindowOption) *RollingWindow {
if size < 1 {
panic("size must be greater than 0")
}
w := &RollingWindow{
size: size,
win: newWindow(size),
interval: interval,
lastTime: timex.Now(),
}
for _, opt := range opts {
opt(w)
}
return w
}
// Add adds value to current bucket.
func (rw *RollingWindow) Add(v float64) {
rw.lock.Lock()
defer rw.lock.Unlock()
rw.updateOffset()
rw.win.add(rw.offset, v)
}
// Reduce runs fn on all buckets, ignore current bucket if ignoreCurrent was set.
func (rw *RollingWindow) Reduce(fn func(b *Bucket)) {
rw.lock.RLock()
defer rw.lock.RUnlock()
var diff int
//獲取跨度,并計(jì)算還有幾個(gè)bucket還在窗口期內(nèi)
span := rw.span()
// ignore current bucket, because of partial data
if span == 0 && rw.ignoreCurrent {
diff = rw.size - 1
} else {
diff = rw.size - span
}
if diff > 0 {
offset := (rw.offset + span + 1) % rw.size
rw.win.reduce(offset, diff, fn)
}
}
//距離上次add操作跨度,
//例如 lastTime = 1s, 當(dāng)前時(shí)間1777ms。樣本窗口時(shí)間250ms,那么跨度為3個(gè)樣本窗口
func (rw *RollingWindow) span() int {
offset := int(timex.Since(rw.lastTime) / rw.interval)
if 0 <= offset && offset < rw.size {
return offset
}
return rw.size
}
//g
func (rw *RollingWindow) updateOffset() {
span := rw.span()
if span <= 0 {
return
}
offset := rw.offset
// reset expired buckets ,重置已經(jīng)超時(shí)的bucket
for i := 0; i < span; i++ {
rw.win.resetBucket((offset + i + 1) % rw.size)
}
rw.offset = (offset + span) % rw.size
now := timex.Now()
//和樣本窗口時(shí)間對(duì)齊
rw.lastTime = now - (now-rw.lastTime)%rw.interval
}三 使用
//1.新建一個(gè)4樣本窗口,每個(gè)樣本窗口250ms
rollingWindow:= NewRollingWindow(4, time.Millisecond*250,IgnoreCurrentBucket())
//2.add
rollingWindow.Add(1)
rollingWindow.Add(2)
time.Sleep(time.Millisecond*250)
rollingWindow.Add(3)
rollingWindow.Add(4)
//3.獲取滑動(dòng)窗口的值
var Sum float64
var total int64
rollingWindow.Reduce(func(b *collection.Bucket) {
Sum += int64(b.Sum)
total += b.Count
})到此這篇關(guān)于golang 實(shí)現(xiàn)時(shí)間滑動(dòng)窗口的文章就介紹到這了,更多相關(guān)golang 時(shí)間滑動(dòng)窗口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang熔斷器的開(kāi)發(fā)過(guò)程詳解
Golang熔斷器是一種用于處理分布式系統(tǒng)中服務(wù)調(diào)用的故障保護(hù)機(jī)制,它可以防止故障服務(wù)的連鎖反應(yīng),提高系統(tǒng)的穩(wěn)定性和可靠性,本文將給大家詳細(xì)的介紹一下Golang熔斷器的開(kāi)發(fā)過(guò)程,需要的朋友可以參考下2023-09-09
golang實(shí)現(xiàn)數(shù)組分割的示例代碼
本文主要介紹了golang實(shí)現(xiàn)數(shù)組分割的示例代碼,要求把數(shù)組分割成多個(gè)正整數(shù)大小的數(shù)組,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12
Go語(yǔ)言中init函數(shù)與匿名函數(shù)使用淺析
這篇文章主要介紹了Go語(yǔ)言中init函數(shù)與匿名函數(shù)使用淺析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-01-01
多階段構(gòu)建優(yōu)化Go?程序Docker鏡像
這篇文章主要為大家介紹了多階段構(gòu)建優(yōu)化Go?程序Docker鏡像,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
詳解go-zero如何實(shí)現(xiàn)計(jì)數(shù)器限流
這篇文章主要來(lái)和大家說(shuō)說(shuō)限流,主要包括計(jì)數(shù)器限流算法以及具體的代碼實(shí)現(xiàn),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-08-08
Go語(yǔ)言實(shí)現(xiàn)本地緩存的策略詳解
今天給大家分享的是Go語(yǔ)言本地緩存的一些內(nèi)容,主要是結(jié)合bigcache和fastcache兩個(gè)優(yōu)秀的開(kāi)源代碼庫(kù),總結(jié)一些設(shè)計(jì)思路和感悟,文章通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07

