From 028e85aceb30911f7db38cdc494f046a2cda21b2 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Tue, 21 Jun 2022 20:46:45 +0800 Subject: [PATCH] fix RT may be 0 (#26) * fix RT may be 0 Co-authored-by: chenzhihui --- Makefile | 4 ++-- ratelimit/bbr/bbr.go | 12 +++++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 9d85157..dde667a 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ PKG_DIR?='' LINTER := bin/golangci-lint $(LINTER): - curl -L https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s v1.42.0 + curl -SL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s latest .PHONY: test test: @@ -21,4 +21,4 @@ lint: $(LINTER) .PHONY: build build: - ${TOOLS_SH} build ${PKG_DIR} \ No newline at end of file + ${TOOLS_SH} build ${PKG_DIR} diff --git a/ratelimit/bbr/bbr.go b/ratelimit/bbr/bbr.go index d53fb16..20fe9f3 100644 --- a/ratelimit/bbr/bbr.go +++ b/ratelimit/bbr/bbr.go @@ -43,12 +43,20 @@ func cpuproc() { for range ticker.C { stat := &cpu.Stat{} cpu.ReadStat(stat) + stat.Usage = min(stat.Usage, 1000) prevCPU := atomic.LoadInt64(&gCPU) curCPU := int64(float64(prevCPU)*decay + float64(stat.Usage)*(1.0-decay)) atomic.StoreInt64(&gCPU, curCPU) } } +func min(l, r uint64) uint64 { + if l < r { + return l + } + return r +} + // Stat contains the metrics snapshot of bbr. type Stat struct { CPU int64 @@ -288,8 +296,10 @@ func (l *BBR) Allow() (ratelimit.DoneFunc, error) { } atomic.AddInt64(&l.inFlight, 1) start := time.Now().UnixNano() + ms := float64(time.Millisecond) return func(ratelimit.DoneInfo) { - rt := (time.Now().UnixNano() - start) / int64(time.Millisecond) + //nolint + rt := int64(math.Ceil(float64(time.Now().UnixNano()-start)) / ms) l.rtStat.Add(rt) atomic.AddInt64(&l.inFlight, -1) l.passStat.Add(1)