github.com/aergoio/aergo@v1.3.1/p2p/metric/etherCopyRate.go (about)

     1  /*
     2   * @file
     3   * @copyright defined in aergo/LICENSE.txt
     4   */
     5  
     6  package metric
     7  
     8  import (
     9  	"math"
    10  	"sync"
    11  	"sync/atomic"
    12  )
    13  
    14  type etherCopyRate struct {
    15  	mutex sync.Mutex
    16  	uncounted int64
    17  	// calculated 
    18  	rate float64
    19  	alpha float64
    20  	init bool
    21  }
    22  
    23  
    24  func NewECRate5(tickInterval int) *etherCopyRate {
    25  	ticIntF := float64(tickInterval)
    26  	return NewECRate(1 - math.Exp(-ticIntF/60.0/5))
    27  }
    28  
    29  func NewECRate(alpha float64) *etherCopyRate {
    30  	return &etherCopyRate{alpha: alpha}
    31  }
    32  
    33  
    34  func (a *etherCopyRate) APS() uint64 {
    35  	return uint64(a.RateF())
    36  }
    37  
    38  func (a *etherCopyRate) LoadScore() uint64 {
    39  	return uint64(a.RateF())
    40  }
    41  
    42  // APS returns the moving average rate of events per second.
    43  func (a *etherCopyRate) RateF() float64 {
    44  	a.mutex.Lock()
    45  	defer a.mutex.Unlock()
    46  	return a.rate * float64(1e9)
    47  }
    48  
    49  func (a *etherCopyRate) Calculate() {
    50  	count := atomic.LoadInt64(&a.uncounted)
    51  	atomic.AddInt64(&a.uncounted, -count)
    52  	instantRate := float64(count) / float64(5e9)
    53  	a.mutex.Lock()
    54  	defer a.mutex.Unlock()
    55  	if a.init {
    56  		a.rate += a.alpha * (instantRate - a.rate)
    57  	} else {
    58  		a.init = true
    59  		a.rate = instantRate
    60  	}
    61  }
    62  
    63  // Update adds n uncounted events.
    64  func (a *etherCopyRate) AddBytes(n int64) {
    65  	atomic.AddInt64(&a.uncounted, n)
    66  }