periodic_sampler.h 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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_PERIODIC_SAMPLER_H_
  15. #define ABSL_PROFILING_INTERNAL_PERIODIC_SAMPLER_H_
  16. #include <stdint.h>
  17. #include <atomic>
  18. #include "absl/base/optimization.h"
  19. #include "absl/profiling/internal/exponential_biased.h"
  20. namespace absl {
  21. ABSL_NAMESPACE_BEGIN
  22. namespace profiling_internal {
  23. // PeriodicSamplerBase provides the basic period sampler implementation.
  24. //
  25. // This is the base class for the templated PeriodicSampler class, which holds
  26. // a global std::atomic value identified by a user defined tag, such that
  27. // each specific PeriodSampler implementation holds its own global period.
  28. //
  29. // PeriodicSamplerBase is thread-compatible except where stated otherwise.
  30. class PeriodicSamplerBase {
  31. public:
  32. // PeriodicSamplerBase is trivial / copyable / movable / destructible.
  33. PeriodicSamplerBase() = default;
  34. PeriodicSamplerBase(PeriodicSamplerBase&&) = default;
  35. PeriodicSamplerBase(const PeriodicSamplerBase&) = default;
  36. // Returns true roughly once every `period` calls. This is established by a
  37. // randomly picked `stride` that is counted down on each call to `Sample`.
  38. // This stride is picked such that the probability of `Sample()` returning
  39. // true is 1 in `period`.
  40. inline bool Sample() noexcept;
  41. // The below methods are intended for optimized use cases where the
  42. // size of the inlined fast path code is highly important. Applications
  43. // should use the `Sample()` method unless they have proof that their
  44. // specific use case requires the optimizations offered by these methods.
  45. //
  46. // An example of such a use case is SwissTable sampling. All sampling checks
  47. // are in inlined SwissTable methods, and the number of call sites is huge.
  48. // In this case, the inlined code size added to each translation unit calling
  49. // SwissTable methods is non-trivial.
  50. //
  51. // The `SubtleMaybeSample()` function spuriously returns true even if the
  52. // function should not be sampled, applications MUST match each call to
  53. // 'SubtleMaybeSample()' returning true with a `SubtleConfirmSample()` call,
  54. // and use the result of the latter as the sampling decision.
  55. // In other words: the code should logically be equivalent to:
  56. //
  57. // if (SubtleMaybeSample() && SubtleConfirmSample()) {
  58. // // Sample this call
  59. // }
  60. //
  61. // In the 'inline-size' optimized case, the `SubtleConfirmSample()` call can
  62. // be placed out of line, for example, the typical use case looks as follows:
  63. //
  64. // // --- frobber.h -----------
  65. // void FrobberSampled();
  66. //
  67. // inline void FrobberImpl() {
  68. // // ...
  69. // }
  70. //
  71. // inline void Frobber() {
  72. // if (ABSL_PREDICT_FALSE(sampler.SubtleMaybeSample())) {
  73. // FrobberSampled();
  74. // } else {
  75. // FrobberImpl();
  76. // }
  77. // }
  78. //
  79. // // --- frobber.cc -----------
  80. // void FrobberSampled() {
  81. // if (!sampler.SubtleConfirmSample())) {
  82. // // Spurious false positive
  83. // FrobberImpl();
  84. // return;
  85. // }
  86. //
  87. // // Sampled execution
  88. // // ...
  89. // }
  90. inline bool SubtleMaybeSample() noexcept;
  91. bool SubtleConfirmSample() noexcept;
  92. protected:
  93. // We explicitly don't use a virtual destructor as this class is never
  94. // virtually destroyed, and it keeps the class trivial, which avoids TLS
  95. // prologue and epilogue code for our TLS instances.
  96. ~PeriodicSamplerBase() = default;
  97. // Returns the next stride for our sampler.
  98. // This function is virtual for testing purposes only.
  99. virtual int64_t GetExponentialBiased(int period) noexcept;
  100. private:
  101. // Returns the current period of this sampler. Thread-safe.
  102. virtual int period() const noexcept = 0;
  103. // Keep and decrement stride_ as an unsigned integer, but compare the value
  104. // to zero casted as a signed int. clang and msvc do not create optimum code
  105. // if we use signed for the combined decrement and sign comparison.
  106. //
  107. // Below 3 alternative options, all compiles generate the best code
  108. // using the unsigned increment <---> signed int comparison option.
  109. //
  110. // Option 1:
  111. // int64_t stride_;
  112. // if (ABSL_PREDICT_TRUE(++stride_ < 0)) { ... }
  113. //
  114. // GCC x64 (OK) : https://gcc.godbolt.org/z/R5MzzA
  115. // GCC ppc (OK) : https://gcc.godbolt.org/z/z7NZAt
  116. // Clang x64 (BAD): https://gcc.godbolt.org/z/t4gPsd
  117. // ICC x64 (OK) : https://gcc.godbolt.org/z/rE6s8W
  118. // MSVC x64 (OK) : https://gcc.godbolt.org/z/ARMXqS
  119. //
  120. // Option 2:
  121. // int64_t stride_ = 0;
  122. // if (ABSL_PREDICT_TRUE(--stride_ >= 0)) { ... }
  123. //
  124. // GCC x64 (OK) : https://gcc.godbolt.org/z/jSQxYK
  125. // GCC ppc (OK) : https://gcc.godbolt.org/z/VJdYaA
  126. // Clang x64 (BAD): https://gcc.godbolt.org/z/Xm4NjX
  127. // ICC x64 (OK) : https://gcc.godbolt.org/z/4snaFd
  128. // MSVC x64 (BAD): https://gcc.godbolt.org/z/BgnEKE
  129. //
  130. // Option 3:
  131. // uint64_t stride_;
  132. // if (ABSL_PREDICT_TRUE(static_cast<int64_t>(++stride_) < 0)) { ... }
  133. //
  134. // GCC x64 (OK) : https://gcc.godbolt.org/z/bFbfPy
  135. // GCC ppc (OK) : https://gcc.godbolt.org/z/S9KkUE
  136. // Clang x64 (OK) : https://gcc.godbolt.org/z/UYzRb4
  137. // ICC x64 (OK) : https://gcc.godbolt.org/z/ptTNfD
  138. // MSVC x64 (OK) : https://gcc.godbolt.org/z/76j4-5
  139. uint64_t stride_ = 0;
  140. absl::profiling_internal::ExponentialBiased rng_;
  141. };
  142. inline bool PeriodicSamplerBase::SubtleMaybeSample() noexcept {
  143. // See comments on `stride_` for the unsigned increment / signed compare.
  144. if (ABSL_PREDICT_TRUE(static_cast<int64_t>(++stride_) < 0)) {
  145. return false;
  146. }
  147. return true;
  148. }
  149. inline bool PeriodicSamplerBase::Sample() noexcept {
  150. return ABSL_PREDICT_FALSE(SubtleMaybeSample()) ? SubtleConfirmSample()
  151. : false;
  152. }
  153. // PeriodicSampler is a concreted periodic sampler implementation.
  154. // The user provided Tag identifies the implementation, and is required to
  155. // isolate the global state of this instance from other instances.
  156. //
  157. // Typical use case:
  158. //
  159. // struct HashTablezTag {};
  160. // thread_local PeriodicSampler<HashTablezTag, 100> sampler;
  161. //
  162. // void HashTableSamplingLogic(...) {
  163. // if (sampler.Sample()) {
  164. // HashTableSlowSamplePath(...);
  165. // }
  166. // }
  167. //
  168. template <typename Tag, int default_period = 0>
  169. class PeriodicSampler final : public PeriodicSamplerBase {
  170. public:
  171. ~PeriodicSampler() = default;
  172. int period() const noexcept final {
  173. return period_.load(std::memory_order_relaxed);
  174. }
  175. // Sets the global period for this sampler. Thread-safe.
  176. // Setting a period of 0 disables the sampler, i.e., every call to Sample()
  177. // will return false. Setting a period of 1 puts the sampler in 'always on'
  178. // mode, i.e., every call to Sample() returns true.
  179. static void SetGlobalPeriod(int period) {
  180. period_.store(period, std::memory_order_relaxed);
  181. }
  182. private:
  183. static std::atomic<int> period_;
  184. };
  185. template <typename Tag, int default_period>
  186. std::atomic<int> PeriodicSampler<Tag, default_period>::period_(default_period);
  187. } // namespace profiling_internal
  188. ABSL_NAMESPACE_END
  189. } // namespace absl
  190. #endif // ABSL_PROFILING_INTERNAL_PERIODIC_SAMPLER_H_