periodic_sampler.cc 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. #include "y_absl/profiling/internal/periodic_sampler.h"
  15. #include <atomic>
  16. #include "y_absl/profiling/internal/exponential_biased.h"
  17. namespace y_absl {
  18. Y_ABSL_NAMESPACE_BEGIN
  19. namespace profiling_internal {
  20. int64_t PeriodicSamplerBase::GetExponentialBiased(int period) noexcept {
  21. return rng_.GetStride(period);
  22. }
  23. bool PeriodicSamplerBase::SubtleConfirmSample() noexcept {
  24. int current_period = period();
  25. // Deal with period case 0 (always off) and 1 (always on)
  26. if (Y_ABSL_PREDICT_FALSE(current_period < 2)) {
  27. stride_ = 0;
  28. return current_period == 1;
  29. }
  30. // Check if this is the first call to Sample()
  31. if (Y_ABSL_PREDICT_FALSE(stride_ == 1)) {
  32. stride_ = static_cast<uint64_t>(-GetExponentialBiased(current_period));
  33. if (static_cast<int64_t>(stride_) < -1) {
  34. ++stride_;
  35. return false;
  36. }
  37. }
  38. stride_ = static_cast<uint64_t>(-GetExponentialBiased(current_period));
  39. return true;
  40. }
  41. } // namespace profiling_internal
  42. Y_ABSL_NAMESPACE_END
  43. } // namespace y_absl