exponential_biased.h 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. // Copyright 2019 The Abseil 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. // https://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. #ifndef ABSL_PROFILING_INTERNAL_EXPONENTIAL_BIASED_H_
  15. #define ABSL_PROFILING_INTERNAL_EXPONENTIAL_BIASED_H_
  16. #include <stdint.h>
  17. #include "absl/base/config.h"
  18. #include "absl/base/macros.h"
  19. namespace absl {
  20. ABSL_NAMESPACE_BEGIN
  21. namespace profiling_internal {
  22. // ExponentialBiased provides a small and fast random number generator for a
  23. // rounded exponential distribution. This generator manages very little state,
  24. // and imposes no synchronization overhead. This makes it useful in specialized
  25. // scenarios requiring minimum overhead, such as stride based periodic sampling.
  26. //
  27. // ExponentialBiased provides two closely related functions, GetSkipCount() and
  28. // GetStride(), both returning a rounded integer defining a number of events
  29. // required before some event with a given mean probability occurs.
  30. //
  31. // The distribution is useful to generate a random wait time or some periodic
  32. // event with a given mean probability. For example, if an action is supposed to
  33. // happen on average once every 'N' events, then we can get a random 'stride'
  34. // counting down how long before the event to happen. For example, if we'd want
  35. // to sample one in every 1000 'Frobber' calls, our code could look like this:
  36. //
  37. // Frobber::Frobber() {
  38. // stride_ = exponential_biased_.GetStride(1000);
  39. // }
  40. //
  41. // void Frobber::Frob(int arg) {
  42. // if (--stride == 0) {
  43. // SampleFrob(arg);
  44. // stride_ = exponential_biased_.GetStride(1000);
  45. // }
  46. // ...
  47. // }
  48. //
  49. // The rounding of the return value creates a bias, especially for smaller means
  50. // where the distribution of the fraction is not evenly distributed. We correct
  51. // this bias by tracking the fraction we rounded up or down on each iteration,
  52. // effectively tracking the distance between the cumulative value, and the
  53. // rounded cumulative value. For example, given a mean of 2:
  54. //
  55. // raw = 1.63076, cumulative = 1.63076, rounded = 2, bias = -0.36923
  56. // raw = 0.14624, cumulative = 1.77701, rounded = 2, bias = 0.14624
  57. // raw = 4.93194, cumulative = 6.70895, rounded = 7, bias = -0.06805
  58. // raw = 0.24206, cumulative = 6.95101, rounded = 7, bias = 0.24206
  59. // etc...
  60. //
  61. // Adjusting with rounding bias is relatively trivial:
  62. //
  63. // double value = bias_ + exponential_distribution(mean)();
  64. // double rounded_value = std::rint(value);
  65. // bias_ = value - rounded_value;
  66. // return rounded_value;
  67. //
  68. // This class is thread-compatible.
  69. class ExponentialBiased {
  70. public:
  71. // The number of bits set by NextRandom.
  72. static constexpr int kPrngNumBits = 48;
  73. // `GetSkipCount()` returns the number of events to skip before some chosen
  74. // event happens. For example, randomly tossing a coin, we will on average
  75. // throw heads once before we get tails. We can simulate random coin tosses
  76. // using GetSkipCount() as:
  77. //
  78. // ExponentialBiased eb;
  79. // for (...) {
  80. // int number_of_heads_before_tail = eb.GetSkipCount(1);
  81. // for (int flips = 0; flips < number_of_heads_before_tail; ++flips) {
  82. // printf("head...");
  83. // }
  84. // printf("tail\n");
  85. // }
  86. //
  87. int64_t GetSkipCount(int64_t mean);
  88. // GetStride() returns the number of events required for a specific event to
  89. // happen. See the class comments for a usage example. `GetStride()` is
  90. // equivalent to `GetSkipCount(mean - 1) + 1`. When to use `GetStride()` or
  91. // `GetSkipCount()` depends mostly on what best fits the use case.
  92. int64_t GetStride(int64_t mean);
  93. // Computes a random number in the range [0, 1<<(kPrngNumBits+1) - 1]
  94. //
  95. // This is public to enable testing.
  96. static uint64_t NextRandom(uint64_t rnd);
  97. private:
  98. void Initialize();
  99. uint64_t rng_{0};
  100. double bias_{0};
  101. bool initialized_{false};
  102. };
  103. // Returns the next prng value.
  104. // pRNG is: aX+b mod c with a = 0x5DEECE66D, b = 0xB, c = 1<<48
  105. // This is the lrand64 generator.
  106. inline uint64_t ExponentialBiased::NextRandom(uint64_t rnd) {
  107. const uint64_t prng_mult = uint64_t{0x5DEECE66D};
  108. const uint64_t prng_add = 0xB;
  109. const uint64_t prng_mod_power = 48;
  110. const uint64_t prng_mod_mask =
  111. ~((~static_cast<uint64_t>(0)) << prng_mod_power);
  112. return (prng_mult * rnd + prng_add) & prng_mod_mask;
  113. }
  114. } // namespace profiling_internal
  115. ABSL_NAMESPACE_END
  116. } // namespace absl
  117. #endif // ABSL_PROFILING_INTERNAL_EXPONENTIAL_BIASED_H_