github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/metric/sliding_histogram.go (about)

     1  // Copyright 2015 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package metric
    12  
    13  import (
    14  	"time"
    15  
    16  	"github.com/codahale/hdrhistogram"
    17  )
    18  
    19  var _ periodic = &slidingHistogram{}
    20  
    21  // A deprecatedWindowedHistogram is a wrapper around an
    22  // hdrhistogram.WindowedHistogram. The caller must enforce proper
    23  // synchronization.
    24  type slidingHistogram struct {
    25  	windowed *hdrhistogram.WindowedHistogram
    26  	nextT    time.Time
    27  	duration time.Duration
    28  }
    29  
    30  // newSlidingHistogram creates a new windowed HDRHistogram with the given
    31  // parameters. Data is kept in the active window for approximately the given
    32  // duration. See the documentation for hdrhistogram.WindowedHistogram for
    33  // details.
    34  func newSlidingHistogram(duration time.Duration, maxVal int64, sigFigs int) *slidingHistogram {
    35  	if duration <= 0 {
    36  		panic("cannot create a sliding histogram with nonpositive duration")
    37  	}
    38  	return &slidingHistogram{
    39  		nextT:    now(),
    40  		duration: duration,
    41  		windowed: hdrhistogram.NewWindowed(histWrapNum, 0, maxVal, sigFigs),
    42  	}
    43  }
    44  
    45  func (h *slidingHistogram) tick() {
    46  	h.nextT = h.nextT.Add(h.duration / histWrapNum)
    47  	h.windowed.Rotate()
    48  }
    49  
    50  func (h *slidingHistogram) nextTick() time.Time {
    51  	return h.nextT
    52  }
    53  
    54  func (h *slidingHistogram) Current() *hdrhistogram.Histogram {
    55  	maybeTick(h)
    56  	return h.windowed.Merge()
    57  }
    58  
    59  func (h *slidingHistogram) RecordValue(v int64) error {
    60  	return h.windowed.Current.RecordValue(v)
    61  }