dubbo.apache.org/dubbo-go/v3@v3.1.1/metrics/util/aggregate/quantile.go (about) 1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package aggregate 19 20 import ( 21 "sync" 22 "time" 23 ) 24 25 import ( 26 "github.com/influxdata/tdigest" 27 ) 28 29 // TimeWindowQuantile wrappers sliding window around T-Digest. 30 // 31 // It is concurrent safe. 32 // It uses T-Digest algorithm to calculate quantile. 33 // The window is divided into several panes, and each pane's value is a TDigest instance. 34 type TimeWindowQuantile struct { 35 compression float64 36 window *slidingWindow 37 mux sync.RWMutex 38 } 39 40 func NewTimeWindowQuantile(compression float64, paneCount int, timeWindowSeconds int64) *TimeWindowQuantile { 41 return &TimeWindowQuantile{ 42 compression: compression, 43 window: newSlidingWindow(paneCount, timeWindowSeconds*1000), 44 } 45 } 46 47 // Quantile returns a quantile of the sliding window by merging all panes. 48 func (t *TimeWindowQuantile) Quantile(q float64) float64 { 49 return t.mergeTDigests().Quantile(q) 50 } 51 52 // Quantiles returns quantiles of the sliding window by merging all panes. 53 func (t *TimeWindowQuantile) Quantiles(qs []float64) []float64 { 54 td := t.mergeTDigests() 55 56 res := make([]float64, len(qs)) 57 for i, q := range qs { 58 res[i] = td.Quantile(q) 59 } 60 61 return res 62 } 63 64 // mergeTDigests merges all panes' TDigests into one TDigest. 65 func (t *TimeWindowQuantile) mergeTDigests() *tdigest.TDigest { 66 t.mux.RLock() 67 defer t.mux.RUnlock() 68 69 td := tdigest.NewWithCompression(t.compression) 70 for _, v := range t.window.values(time.Now().UnixMilli()) { 71 td.AddCentroidList(v.(*tdigest.TDigest).Centroids()) 72 } 73 return td 74 } 75 76 // Add adds a value to the sliding window's current pane. 77 func (t *TimeWindowQuantile) Add(value float64) { 78 t.mux.Lock() 79 defer t.mux.Unlock() 80 81 t.window.currentPane(time.Now().UnixMilli(), t.newEmptyValue).value.(*tdigest.TDigest).Add(value, 1) 82 } 83 84 func (t *TimeWindowQuantile) newEmptyValue() interface{} { 85 return tdigest.NewWithCompression(t.compression) 86 }