1package main 2 3import ( 4 "runtime" 5 "strconv" 6 "time" 7) 8 9type GorStat struct { 10 statName string 11 rateMs int 12 latest int 13 mean int 14 max int 15 count int 16} 17 18func NewGorStat(statName string, rateMs int) (s *GorStat) { 19 s = new(GorStat) 20 s.statName = statName 21 s.rateMs = rateMs 22 s.latest = 0 23 s.mean = 0 24 s.max = 0 25 s.count = 0 26 27 if Settings.Stats { 28 go s.reportStats() 29 } 30 return 31} 32 33func (s *GorStat) Write(latest int) { 34 if Settings.Stats { 35 if latest > s.max { 36 s.max = latest 37 } 38 if latest != 0 { 39 s.mean = ((s.mean * s.count) + latest) / (s.count + 1) 40 } 41 s.latest = latest 42 s.count = s.count + 1 43 } 44} 45 46func (s *GorStat) Reset() { 47 s.latest = 0 48 s.max = 0 49 s.mean = 0 50 s.count = 0 51} 52 53func (s *GorStat) String() string { 54 return s.statName + ":" + strconv.Itoa(s.latest) + "," + strconv.Itoa(s.mean) + "," + strconv.Itoa(s.max) + "," + strconv.Itoa(s.count) + "," + strconv.Itoa(s.count/(s.rateMs/1000.0)) + "," + strconv.Itoa(runtime.NumGoroutine()) 55} 56 57func (s *GorStat) reportStats() { 58 Debug(0, "\n", s.statName+":latest,mean,max,count,count/second,gcount") 59 for { 60 Debug(0, "\n", s) 61 s.Reset() 62 time.Sleep(time.Duration(s.rateMs) * time.Millisecond) 63 } 64} 65