You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

exponential_biased.h 5.8 kB

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