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 
15 #ifndef ABSL_STRINGS_INTERNAL_CORDZ_FUNCTIONS_H_
16 #define ABSL_STRINGS_INTERNAL_CORDZ_FUNCTIONS_H_
17 
18 #include <stdint.h>
19 
20 #include "absl/base/attributes.h"
21 #include "absl/base/config.h"
22 #include "absl/base/optimization.h"
23 
24 namespace absl {
25 ABSL_NAMESPACE_BEGIN
26 namespace cord_internal {
27 
28 // Returns the current sample rate. This represents the average interval
29 // between samples.
30 int32_t get_cordz_mean_interval();
31 
32 // Sets the sample rate with the average interval between samples.
33 void set_cordz_mean_interval(int32_t mean_interval);
34 
35 // Cordz is only enabled on Linux with thread_local support.
36 #if defined(ABSL_INTERNAL_CORDZ_ENABLED)
37 #error ABSL_INTERNAL_CORDZ_ENABLED cannot be set directly
38 #elif defined(__linux__) && defined(ABSL_HAVE_THREAD_LOCAL)
39 #define ABSL_INTERNAL_CORDZ_ENABLED 1
40 #endif
41 
42 #ifdef ABSL_INTERNAL_CORDZ_ENABLED
43 
44 // cordz_next_sample is the number of events until the next sample event. If
45 // the value is 1 or less, the code will check on the next event if cordz is
46 // enabled, and if so, will sample the Cord. cordz is only enabled when we can
47 // use thread locals.
48 ABSL_CONST_INIT extern thread_local int64_t cordz_next_sample;
49 
50 // Determines if the next sample should be profiled. If it is, the value pointed
51 // at by next_sample will be set with the interval until the next sample.
52 bool cordz_should_profile_slow();
53 
54 // Returns true if the next cord should be sampled.
cordz_should_profile()55 inline bool cordz_should_profile() {
56   if (ABSL_PREDICT_TRUE(cordz_next_sample > 1)) {
57     cordz_next_sample--;
58     return false;
59   }
60   return cordz_should_profile_slow();
61 }
62 
63 // Sets the interval until the next sample (for testing only)
64 void cordz_set_next_sample_for_testing(int64_t next_sample);
65 
66 #else  // ABSL_INTERNAL_CORDZ_ENABLED
67 
cordz_should_profile()68 inline bool cordz_should_profile() { return false; }
cordz_set_next_sample_for_testing(int64_t)69 inline void cordz_set_next_sample_for_testing(int64_t) {}
70 
71 #endif  // ABSL_INTERNAL_CORDZ_ENABLED
72 
73 }  // namespace cord_internal
74 ABSL_NAMESPACE_END
75 }  // namespace absl
76 
77 #endif  // ABSL_STRINGS_INTERNAL_CORDZ_FUNCTIONS_H_
78