| 1 |
// Copyright 2021 gRPC authors. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
#include <grpc/support/port_platform.h> |
| 16 |
|
| 17 |
#include "src/core/lib/debug/histogram_view.h" |
| 18 |
|
| 19 |
namespace grpc_core { |
| 20 |
|
| 21 |
double HistogramView::Count() const { |
| 22 |
double sum = 0; |
| 23 |
for (int i = 0; i < num_buckets; i++) { |
| 24 |
sum += buckets[i]; |
| 25 |
} |
| 26 |
return sum; |
| 27 |
} |
| 28 |
|
| 29 |
double HistogramView::ThresholdForCountBelow(double count_below) const { |
| 30 |
double lower_bound; |
| 31 |
double upper_bound; |
| 32 |
int upper_idx; |
| 33 |
|
| 34 |
// find the lowest bucket that gets us above count_below |
| 35 |
double count_so_far = 0.0; |
| 36 |
int lower_idx = 0; |
| 37 |
for (; lower_idx < num_buckets; lower_idx++) { |
| 38 |
count_so_far += static_cast<double>(buckets[lower_idx]); |
| 39 |
if (count_so_far >= count_below) { |
| 40 |
break; |
| 41 |
} |
| 42 |
} |
| 43 |
if (count_so_far == count_below) { |
| 44 |
// this bucket hits the threshold exactly... we should be midway through |
| 45 |
// any run of zero values following the bucket |
| 46 |
for (upper_idx = lower_idx + 1; upper_idx < num_buckets; upper_idx++) { |
| 47 |
if (buckets[upper_idx]) { |
| 48 |
break; |
| 49 |
} |
| 50 |
} |
| 51 |
return (bucket_boundaries[lower_idx] + bucket_boundaries[upper_idx]) / 2.0; |
| 52 |
} else { |
| 53 |
// treat values as uniform throughout the bucket, and find where this value |
| 54 |
// should lie |
| 55 |
lower_bound = bucket_boundaries[lower_idx]; |
| 56 |
upper_bound = bucket_boundaries[lower_idx + 1]; |
| 57 |
return upper_bound - (upper_bound - lower_bound) * |
| 58 |
(count_so_far - count_below) / |
| 59 |
static_cast<double>(buckets[lower_idx]); |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
double HistogramView::Percentile(double p) const { |
| 64 |
const double count = Count(); |
| 65 |
if (count == 0) return 0.0; |
| 66 |
return ThresholdForCountBelow(count * p / 100.0); |
| 67 |
} |
| 68 |
|
| 69 |
} // namespace grpc_core |