histogram.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #include "monitoring/histogram.h"
  10. #include <algorithm>
  11. #include <cassert>
  12. #include <cinttypes>
  13. #include <cmath>
  14. #include <cstdio>
  15. #include "port/port.h"
  16. #include "util/cast_util.h"
  17. namespace ROCKSDB_NAMESPACE {
  18. HistogramBucketMapper::HistogramBucketMapper() {
  19. // If you change this, you also need to change
  20. // size of array buckets_ in HistogramImpl
  21. bucketValues_ = {1, 2};
  22. double bucket_val = static_cast<double>(bucketValues_.back());
  23. while ((bucket_val = 1.5 * bucket_val) <=
  24. static_cast<double>(std::numeric_limits<uint64_t>::max())) {
  25. bucketValues_.push_back(static_cast<uint64_t>(bucket_val));
  26. // Extracts two most significant digits to make histogram buckets more
  27. // human-readable. E.g., 172 becomes 170.
  28. uint64_t pow_of_ten = 1;
  29. while (bucketValues_.back() / 10 > 10) {
  30. bucketValues_.back() /= 10;
  31. pow_of_ten *= 10;
  32. }
  33. bucketValues_.back() *= pow_of_ten;
  34. }
  35. maxBucketValue_ = bucketValues_.back();
  36. minBucketValue_ = bucketValues_.front();
  37. }
  38. size_t HistogramBucketMapper::IndexForValue(const uint64_t value) const {
  39. auto beg = bucketValues_.begin();
  40. auto end = bucketValues_.end();
  41. if (value >= maxBucketValue_) {
  42. return end - beg - 1; // bucketValues_.size() - 1
  43. } else {
  44. return std::lower_bound(beg, end, value) - beg;
  45. }
  46. }
  47. namespace {
  48. const HistogramBucketMapper bucketMapper;
  49. }
  50. HistogramStat::HistogramStat() : num_buckets_(bucketMapper.BucketCount()) {
  51. assert(num_buckets_ == sizeof(buckets_) / sizeof(*buckets_));
  52. Clear();
  53. }
  54. void HistogramStat::Clear() {
  55. min_.store(bucketMapper.LastValue(), std::memory_order_relaxed);
  56. max_.store(0, std::memory_order_relaxed);
  57. num_.store(0, std::memory_order_relaxed);
  58. sum_.store(0, std::memory_order_relaxed);
  59. sum_squares_.store(0, std::memory_order_relaxed);
  60. for (unsigned int b = 0; b < num_buckets_; b++) {
  61. buckets_[b].store(0, std::memory_order_relaxed);
  62. }
  63. }
  64. bool HistogramStat::Empty() const { return num() == 0; }
  65. void HistogramStat::Add(uint64_t value) {
  66. // This function is designed to be lock free, as it's in the critical path
  67. // of any operation. Each individual value is atomic and the order of updates
  68. // by concurrent threads is tolerable.
  69. const size_t index = bucketMapper.IndexForValue(value);
  70. assert(index < num_buckets_);
  71. buckets_[index].store(buckets_[index].load(std::memory_order_relaxed) + 1,
  72. std::memory_order_relaxed);
  73. uint64_t old_min = min();
  74. if (value < old_min) {
  75. min_.store(value, std::memory_order_relaxed);
  76. }
  77. uint64_t old_max = max();
  78. if (value > old_max) {
  79. max_.store(value, std::memory_order_relaxed);
  80. }
  81. num_.store(num_.load(std::memory_order_relaxed) + 1,
  82. std::memory_order_relaxed);
  83. sum_.store(sum_.load(std::memory_order_relaxed) + value,
  84. std::memory_order_relaxed);
  85. sum_squares_.store(
  86. sum_squares_.load(std::memory_order_relaxed) + value * value,
  87. std::memory_order_relaxed);
  88. }
  89. void HistogramStat::Merge(const HistogramStat& other) {
  90. // This function needs to be performned with the outer lock acquired
  91. // However, atomic operation on every member is still need, since Add()
  92. // requires no lock and value update can still happen concurrently
  93. uint64_t old_min = min();
  94. uint64_t other_min = other.min();
  95. while (other_min < old_min &&
  96. !min_.compare_exchange_weak(old_min, other_min)) {
  97. }
  98. uint64_t old_max = max();
  99. uint64_t other_max = other.max();
  100. while (other_max > old_max &&
  101. !max_.compare_exchange_weak(old_max, other_max)) {
  102. }
  103. num_.fetch_add(other.num(), std::memory_order_relaxed);
  104. sum_.fetch_add(other.sum(), std::memory_order_relaxed);
  105. sum_squares_.fetch_add(other.sum_squares(), std::memory_order_relaxed);
  106. for (unsigned int b = 0; b < num_buckets_; b++) {
  107. buckets_[b].fetch_add(other.bucket_at(b), std::memory_order_relaxed);
  108. }
  109. }
  110. double HistogramStat::Median() const { return Percentile(50.0); }
  111. double HistogramStat::Percentile(double p) const {
  112. double threshold = num() * (p / 100.0);
  113. uint64_t cumulative_sum = 0;
  114. for (unsigned int b = 0; b < num_buckets_; b++) {
  115. uint64_t bucket_value = bucket_at(b);
  116. cumulative_sum += bucket_value;
  117. if (cumulative_sum >= threshold) {
  118. // Scale linearly within this bucket
  119. uint64_t left_point = (b == 0) ? 0 : bucketMapper.BucketLimit(b - 1);
  120. uint64_t right_point = bucketMapper.BucketLimit(b);
  121. uint64_t left_sum = cumulative_sum - bucket_value;
  122. uint64_t right_sum = cumulative_sum;
  123. double pos = 0;
  124. uint64_t right_left_diff = right_sum - left_sum;
  125. if (right_left_diff != 0) {
  126. pos = (threshold - left_sum) / right_left_diff;
  127. }
  128. double r = left_point + (right_point - left_point) * pos;
  129. uint64_t cur_min = min();
  130. uint64_t cur_max = max();
  131. if (r < cur_min) {
  132. r = static_cast<double>(cur_min);
  133. }
  134. if (r > cur_max) {
  135. r = static_cast<double>(cur_max);
  136. }
  137. return r;
  138. }
  139. }
  140. return static_cast<double>(max());
  141. }
  142. double HistogramStat::Average() const {
  143. uint64_t cur_num = num();
  144. uint64_t cur_sum = sum();
  145. if (cur_num == 0) {
  146. return 0;
  147. }
  148. return static_cast<double>(cur_sum) / static_cast<double>(cur_num);
  149. }
  150. double HistogramStat::StandardDeviation() const {
  151. double cur_num =
  152. static_cast<double>(num()); // Use double to avoid integer overflow
  153. double cur_sum = static_cast<double>(sum());
  154. double cur_sum_squares = static_cast<double>(sum_squares());
  155. if (cur_num == 0.0) {
  156. return 0.0;
  157. }
  158. double variance =
  159. (cur_sum_squares * cur_num - cur_sum * cur_sum) / (cur_num * cur_num);
  160. return std::sqrt(std::max(variance, 0.0));
  161. }
  162. std::string HistogramStat::ToString() const {
  163. uint64_t cur_num = num();
  164. std::string r;
  165. char buf[1650];
  166. snprintf(buf, sizeof(buf), "Count: %" PRIu64 " Average: %.4f StdDev: %.2f\n",
  167. cur_num, Average(), StandardDeviation());
  168. r.append(buf);
  169. snprintf(buf, sizeof(buf),
  170. "Min: %" PRIu64 " Median: %.4f Max: %" PRIu64 "\n",
  171. (cur_num == 0 ? 0 : min()), Median(), (cur_num == 0 ? 0 : max()));
  172. r.append(buf);
  173. snprintf(buf, sizeof(buf),
  174. "Percentiles: "
  175. "P50: %.2f P75: %.2f P99: %.2f P99.9: %.2f P99.99: %.2f\n",
  176. Percentile(50), Percentile(75), Percentile(99), Percentile(99.9),
  177. Percentile(99.99));
  178. r.append(buf);
  179. r.append("------------------------------------------------------\n");
  180. if (cur_num == 0) {
  181. return r; // all buckets are empty
  182. }
  183. const double mult = 100.0 / cur_num;
  184. uint64_t cumulative_sum = 0;
  185. for (unsigned int b = 0; b < num_buckets_; b++) {
  186. uint64_t bucket_value = bucket_at(b);
  187. if (bucket_value <= 0.0) {
  188. continue;
  189. }
  190. cumulative_sum += bucket_value;
  191. snprintf(buf, sizeof(buf),
  192. "%c %7" PRIu64 ", %7" PRIu64 " ] %8" PRIu64 " %7.3f%% %7.3f%% ",
  193. (b == 0) ? '[' : '(',
  194. (b == 0) ? 0 : bucketMapper.BucketLimit(b - 1), // left
  195. bucketMapper.BucketLimit(b), // right
  196. bucket_value, // count
  197. (mult * bucket_value), // percentage
  198. (mult * cumulative_sum)); // cumulative percentage
  199. r.append(buf);
  200. // Add hash marks based on percentage; 20 marks for 100%.
  201. size_t marks = static_cast<size_t>(mult * bucket_value / 5 + 0.5);
  202. r.append(marks, '#');
  203. r.push_back('\n');
  204. }
  205. return r;
  206. }
  207. void HistogramStat::Data(HistogramData* const data) const {
  208. assert(data);
  209. data->median = Median();
  210. data->percentile95 = Percentile(95);
  211. data->percentile99 = Percentile(99);
  212. data->max = static_cast<double>(max());
  213. data->average = Average();
  214. data->standard_deviation = StandardDeviation();
  215. data->count = num();
  216. data->sum = sum();
  217. data->min = static_cast<double>(min());
  218. }
  219. void HistogramImpl::Clear() {
  220. std::lock_guard<std::mutex> lock(mutex_);
  221. stats_.Clear();
  222. }
  223. bool HistogramImpl::Empty() const { return stats_.Empty(); }
  224. void HistogramImpl::Add(uint64_t value) { stats_.Add(value); }
  225. void HistogramImpl::Merge(const Histogram& other) {
  226. if (strcmp(Name(), other.Name()) == 0) {
  227. Merge(*static_cast_with_check<const HistogramImpl>(&other));
  228. }
  229. }
  230. void HistogramImpl::Merge(const HistogramImpl& other) {
  231. std::lock_guard<std::mutex> lock(mutex_);
  232. stats_.Merge(other.stats_);
  233. }
  234. double HistogramImpl::Median() const { return stats_.Median(); }
  235. double HistogramImpl::Percentile(double p) const {
  236. return stats_.Percentile(p);
  237. }
  238. double HistogramImpl::Average() const { return stats_.Average(); }
  239. double HistogramImpl::StandardDeviation() const {
  240. return stats_.StandardDeviation();
  241. }
  242. std::string HistogramImpl::ToString() const { return stats_.ToString(); }
  243. void HistogramImpl::Data(HistogramData* const data) const { stats_.Data(data); }
  244. } // namespace ROCKSDB_NAMESPACE