github.com/zuoyebang/bitalostable@v1.0.1-0.20240229032404-e3b99a834294/internal/base/metrics.go (about) 1 // Copyright 2022 The LevelDB-Go and Pebble Authors. All rights reserved. Use 2 // of this source code is governed by a BSD-style license that can be found in 3 // the LICENSE file. 4 5 package base 6 7 import "time" 8 9 // ThroughputMetric is used to measure the byte throughput of some component 10 // that performs work in a single-threaded manner. The throughput can be 11 // approximated by Bytes/(WorkDuration+IdleTime). The idle time is represented 12 // separately, so that the user of this metric could approximate the peak 13 // throughput as Bytes/WorkTime. The metric is designed to be cumulative (see 14 // Merge). 15 type ThroughputMetric struct { 16 // Bytes is the processes bytes by the component. 17 Bytes int64 18 // WorkDuration is the duration that the component spent doing work. 19 WorkDuration time.Duration 20 // IdleDuration is the duration that the component was idling, waiting for 21 // work. 22 IdleDuration time.Duration 23 } 24 25 // Merge accumulates the information from another throughput metric. 26 func (tm *ThroughputMetric) Merge(x ThroughputMetric) { 27 tm.Bytes += x.Bytes 28 tm.WorkDuration += x.WorkDuration 29 tm.IdleDuration += x.IdleDuration 30 } 31 32 // PeakRate returns the approximate peak rate if there was no idling. 33 func (tm *ThroughputMetric) PeakRate() int64 { 34 if tm.Bytes == 0 { 35 return 0 36 } 37 return int64((float64(tm.Bytes) / float64(tm.WorkDuration)) * float64(time.Second)) 38 } 39 40 // Rate returns the observed rate. 41 func (tm *ThroughputMetric) Rate() int64 { 42 if tm.Bytes == 0 { 43 return 0 44 } 45 return int64((float64(tm.Bytes) / float64(tm.WorkDuration+tm.IdleDuration)) * 46 float64(time.Second)) 47 } 48 49 // GaugeSampleMetric is used to measure a gauge value (e.g. queue length) by 50 // accumulating samples of that gauge. 51 type GaugeSampleMetric struct { 52 // The sum of all the samples. 53 sampleSum int64 54 // The number of samples. 55 count int64 56 } 57 58 // AddSample adds the given sample. 59 func (gsm *GaugeSampleMetric) AddSample(sample int64) { 60 gsm.sampleSum += sample 61 gsm.count++ 62 } 63 64 // Merge accumulates the information from another gauge metric. 65 func (gsm *GaugeSampleMetric) Merge(x GaugeSampleMetric) { 66 gsm.sampleSum += x.sampleSum 67 gsm.count += x.count 68 } 69 70 // Mean returns the mean value. 71 func (gsm *GaugeSampleMetric) Mean() float64 { 72 if gsm.count == 0 { 73 return 0 74 } 75 return float64(gsm.sampleSum) / float64(gsm.count) 76 }