github.com/pingcap/br@v5.3.0-alpha.0.20220125034240-ec59c7b6ce30+incompatible/pkg/logutil/rate.go (about)

     1  // Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
     2  
     3  package logutil
     4  
     5  import (
     6  	"fmt"
     7  	"time"
     8  
     9  	"github.com/pingcap/log"
    10  	"github.com/prometheus/client_golang/prometheus"
    11  	"go.uber.org/zap"
    12  
    13  	"github.com/pingcap/br/pkg/lightning/metric"
    14  )
    15  
    16  // MetricTableCreatedCounter counts how many tables created.
    17  // TODO: when br decided to introduce Prometheus, move this to its metric package.
    18  var MetricTableCreatedCounter = prometheus.NewCounter(prometheus.CounterOpts{
    19  	Namespace: "BR",
    20  	Name:      "table_created",
    21  	Help:      "The count of tables have been created.",
    22  })
    23  
    24  // RateTracer is a trivial rate tracer based on a promethues counter.
    25  // It traces the average speed from it was created.
    26  type RateTracer struct {
    27  	start time.Time
    28  	base  float64
    29  	prometheus.Counter
    30  }
    31  
    32  // TraceRateOver make a trivial rater based on a counter.
    33  // the current value of this counter would be omitted.
    34  func TraceRateOver(counter prometheus.Counter) RateTracer {
    35  	return RateTracer{
    36  		start:   time.Now(),
    37  		Counter: counter,
    38  		base:    metric.ReadCounter(counter),
    39  	}
    40  }
    41  
    42  // Rate returns the average rate from when it was created.
    43  func (r *RateTracer) Rate() float64 {
    44  	return r.RateAt(time.Now())
    45  }
    46  
    47  // RateAt returns the rate until some instant. This function is mainly for testing.
    48  // WARN: the counter value for calculating is still its CURRENT VALUE.
    49  func (r *RateTracer) RateAt(instant time.Time) float64 {
    50  	return (metric.ReadCounter(r.Counter) - r.base) / instant.Sub(r.start).Seconds()
    51  }
    52  
    53  // L make a logger with the current speed.
    54  func (r *RateTracer) L() *zap.Logger {
    55  	return log.With(zap.String("speed", fmt.Sprintf("%.2f ops/s", r.Rate())))
    56  }