File: floatcounter.go

package info (click to toggle)
golang-github-victoriametrics-metrics 1.35.2%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 308 kB
  • sloc: makefile: 2
file content (86 lines) | stat: -rw-r--r-- 1,946 bytes parent folder | download
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package metrics

import (
	"fmt"
	"io"
	"sync"
)

// NewFloatCounter registers and returns new counter of float64 type with the given name.
//
// name must be valid Prometheus-compatible metric with possible labels.
// For instance,
//
//   - foo
//   - foo{bar="baz"}
//   - foo{bar="baz",aaa="b"}
//
// The returned counter is safe to use from concurrent goroutines.
func NewFloatCounter(name string) *FloatCounter {
	return defaultSet.NewFloatCounter(name)
}

// FloatCounter is a float64 counter guarded by RWmutex.
//
// It may be used as a gauge if Add and Sub are called.
type FloatCounter struct {
	mu sync.Mutex
	n  float64
}

// Add adds n to fc.
func (fc *FloatCounter) Add(n float64) {
	fc.mu.Lock()
	fc.n += n
	fc.mu.Unlock()
}

// Sub substracts n from fc.
func (fc *FloatCounter) Sub(n float64) {
	fc.mu.Lock()
	fc.n -= n
	fc.mu.Unlock()
}

// Get returns the current value for fc.
func (fc *FloatCounter) Get() float64 {
	fc.mu.Lock()
	n := fc.n
	fc.mu.Unlock()
	return n
}

// Set sets fc value to n.
func (fc *FloatCounter) Set(n float64) {
	fc.mu.Lock()
	fc.n = n
	fc.mu.Unlock()
}

// marshalTo marshals fc with the given prefix to w.
func (fc *FloatCounter) marshalTo(prefix string, w io.Writer) {
	v := fc.Get()
	fmt.Fprintf(w, "%s %g\n", prefix, v)
}

func (fc *FloatCounter) metricType() string {
	return "counter"
}

// GetOrCreateFloatCounter returns registered FloatCounter with the given name
// or creates new FloatCounter if the registry doesn't contain FloatCounter with
// the given name.
//
// name must be valid Prometheus-compatible metric with possible labels.
// For instance,
//
//   - foo
//   - foo{bar="baz"}
//   - foo{bar="baz",aaa="b"}
//
// The returned FloatCounter is safe to use from concurrent goroutines.
//
// Performance tip: prefer NewFloatCounter instead of GetOrCreateFloatCounter.
func GetOrCreateFloatCounter(name string) *FloatCounter {
	return defaultSet.GetOrCreateFloatCounter(name)
}