github.com/TeaOSLab/EdgeNode@v1.3.8/internal/trackers/manager.go (about)

     1  // Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
     2  
     3  package trackers
     4  
     5  import (
     6  	"sync"
     7  )
     8  
     9  var SharedManager = NewManager()
    10  
    11  type Manager struct {
    12  	m      map[string][]float64 // label => time costs ms
    13  	locker sync.Mutex
    14  }
    15  
    16  func NewManager() *Manager {
    17  	return &Manager{m: map[string][]float64{}}
    18  }
    19  
    20  func (this *Manager) Add(label string, costMs float64) {
    21  	this.locker.Lock()
    22  	costs, ok := this.m[label]
    23  	if ok {
    24  		costs = append(costs, costMs)
    25  		if len(costs) > 5 { // 只取最近的N条
    26  			costs = costs[1:]
    27  		}
    28  		this.m[label] = costs
    29  	} else {
    30  		this.m[label] = []float64{costMs}
    31  	}
    32  	this.locker.Unlock()
    33  }
    34  
    35  func (this *Manager) Labels() map[string]float64 {
    36  	var result = map[string]float64{}
    37  	this.locker.Lock()
    38  	for label, costs := range this.m {
    39  		var sum float64
    40  		for _, cost := range costs {
    41  			sum += cost
    42  		}
    43  		result[label] = sum / float64(len(costs))
    44  	}
    45  	this.locker.Unlock()
    46  	return result
    47  }