yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/multicloud/azure/progress/computeStats.go (about) 1 // Copyright 2019 Yunion 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package progress 16 17 // ComputeStats type supports computing running average with a given window size. 18 // 19 type ComputeStats struct { 20 history []float64 21 size int 22 p int 23 } 24 25 // NewComputeStats returns a new instance of ComputeStats. The parameter size is the 26 // maximum number of values that ComputeStats track at any given point of time. 27 // 28 func NewComputeStats(size int) *ComputeStats { 29 return &ComputeStats{ 30 history: make([]float64, size), 31 size: size, 32 p: 0, 33 } 34 } 35 36 // NewComputestateDefaultSize returns a new instance of ComputeStats that can tracks 37 // maximum of 60 values. 38 // 39 func NewComputestateDefaultSize() *ComputeStats { 40 return NewComputeStats(60) 41 } 42 43 // ComputeAvg adds the given value to a list containing set of previous values added 44 // and returns the average of the values in the list. If the values list reached the 45 // maximum size then oldest value will be removed 46 // 47 func (s *ComputeStats) ComputeAvg(current float64) float64 { 48 s.history[s.p] = current 49 s.p++ 50 if s.p == s.size { 51 s.p = 0 52 } 53 54 sum := float64(0) 55 for i := 0; i < s.size; i++ { 56 sum += s.history[i] 57 } 58 59 return sum / float64(s.size) 60 }