aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/stat/avg.go
blob: fcfc9f5d52ef11a3f4d019224cde0fa90c003c14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Copyright 2024 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package stat

import (
	"sync"
	"time"
)

type AverageParameter interface {
	time.Duration
}

type AverageValue[T AverageParameter] struct {
	mu    sync.Mutex
	total int64
	avg   T
}

func (av *AverageValue[T]) Value() T {
	av.mu.Lock()
	defer av.mu.Unlock()
	return av.avg
}

func (av *AverageValue[T]) Save(val T) {
	av.mu.Lock()
	defer av.mu.Unlock()
	av.total++
	av.avg += (val - av.avg) / T(av.total)
}