github.com/TeaOSLab/EdgeNode@v1.3.8/internal/rpc/call_stat.go (about) 1 // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn . 2 3 package rpc 4 5 import ( 6 "sync" 7 ) 8 9 type callStatItem struct { 10 ok bool 11 costSeconds float64 12 } 13 14 type CallStat struct { 15 size int 16 items []*callStatItem 17 18 locker sync.Mutex 19 } 20 21 func NewCallStat(size int) *CallStat { 22 return &CallStat{ 23 size: size, 24 } 25 } 26 27 func (this *CallStat) Add(ok bool, costSeconds float64) { 28 var size = this.size 29 if size <= 0 { 30 size = 10 31 } 32 33 this.locker.Lock() 34 this.items = append(this.items, &callStatItem{ 35 ok: ok, 36 costSeconds: costSeconds, 37 }) 38 if len(this.items) > size { 39 this.items = this.items[1:] 40 } 41 this.locker.Unlock() 42 } 43 44 func (this *CallStat) Sum() (successPercent float64, avgCostSeconds float64) { 45 this.locker.Lock() 46 defer this.locker.Unlock() 47 48 var size = this.size 49 if size <= 0 { 50 size = 10 51 } 52 53 var totalItems = len(this.items) 54 if totalItems <= size/2 /** 低于一半的采样率,不计入统计 **/ { 55 successPercent = 100 56 return 57 } 58 59 var totalOkItems = 0 60 var totalCostSeconds float64 61 for _, item := range this.items { 62 if item.ok { 63 totalOkItems++ 64 } 65 totalCostSeconds += item.costSeconds 66 } 67 successPercent = float64(totalOkItems) * 100 / float64(totalItems) 68 avgCostSeconds = totalCostSeconds / float64(totalItems) 69 70 return 71 }