github.com/Microsoft/azure-vhd-utils@v0.0.0-20230613175315-7c30a3748a1b/upload/progress/computeStats.go (about)

     1  package progress
     2  
     3  // ComputeStats type supports computing running average with a given window size.
     4  //
     5  type ComputeStats struct {
     6  	history []float64
     7  	size    int
     8  	p       int
     9  }
    10  
    11  // NewComputeStats returns a new instance of ComputeStats. The parameter size is the
    12  // maximum number of values that ComputeStats track at any given point of time.
    13  //
    14  func NewComputeStats(size int) *ComputeStats {
    15  	return &ComputeStats{
    16  		history: make([]float64, size),
    17  		size:    size,
    18  		p:       0,
    19  	}
    20  }
    21  
    22  // NewComputestateDefaultSize returns a new instance of ComputeStats that can tracks
    23  // maximum of 60 values.
    24  //
    25  func NewComputestateDefaultSize() *ComputeStats {
    26  	return NewComputeStats(60)
    27  }
    28  
    29  // ComputeAvg adds the given value to a list containing set of previous values added
    30  // and returns the average of the values in the list. If the values list reached the
    31  // maximum size then oldest value will be removed
    32  //
    33  func (s *ComputeStats) ComputeAvg(current float64) float64 {
    34  	s.history[s.p] = current
    35  	s.p++
    36  	if s.p == s.size {
    37  		s.p = 0
    38  	}
    39  
    40  	sum := float64(0)
    41  	for i := 0; i < s.size; i++ {
    42  		sum += s.history[i]
    43  	}
    44  
    45  	return sum / float64(s.size)
    46  }