forked from pingcap/br
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rate.go
56 lines (46 loc) · 1.6 KB
/
rate.go
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
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package logutil
import (
"fmt"
"time"
"github.com/pingcap/log"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"github.com/pingcap/br/pkg/lightning/metric"
)
// MetricTableCreatedCounter counts how many tables created.
// TODO: when br decided to introduce Prometheus, move this to its metric package.
var MetricTableCreatedCounter = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "BR",
Name: "table_created",
Help: "The count of tables have been created.",
})
// RateTracer is a trivial rate tracer based on a promethues counter.
// It traces the average speed from it was created.
type RateTracer struct {
start time.Time
base float64
prometheus.Counter
}
// TraceRateOver make a trivial rater based on a counter.
// the current value of this counter would be omitted.
func TraceRateOver(counter prometheus.Counter) RateTracer {
return RateTracer{
start: time.Now(),
Counter: counter,
base: metric.ReadCounter(counter),
}
}
// Rate returns the average rate from when it was created.
func (r *RateTracer) Rate() float64 {
return r.RateAt(time.Now())
}
// RateAt returns the rate until some instant. This function is mainly for testing.
// WARN: the counter value for calculating is still its CURRENT VALUE.
func (r *RateTracer) RateAt(instant time.Time) float64 {
return (metric.ReadCounter(r.Counter) - r.base) / instant.Sub(r.start).Seconds()
}
// L make a logger with the current speed.
func (r *RateTracer) L() *zap.Logger {
return log.With(zap.String("speed", fmt.Sprintf("%.2f ops/s", r.Rate())))
}