xref: /aosp_15_r20/external/grpc-grpc/src/core/lib/transport/call_size_estimator.h (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Copyright 2024 gRPC 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 //     http://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 GRPC_SRC_CORE_LIB_TRANSPORT_CALL_SIZE_ESTIMATOR_H
16 #define GRPC_SRC_CORE_LIB_TRANSPORT_CALL_SIZE_ESTIMATOR_H
17 
18 #include <grpc/support/port_platform.h>
19 
20 #include <stddef.h>
21 
22 #include <atomic>
23 
24 namespace grpc_core {
25 
26 class CallSizeEstimator {
27  public:
CallSizeEstimator(size_t initial_estimate)28   explicit CallSizeEstimator(size_t initial_estimate)
29       : call_size_estimate_(initial_estimate) {}
30 
CallSizeEstimate()31   size_t CallSizeEstimate() {
32     // We round up our current estimate to the NEXT value of kRoundUpSize.
33     // This ensures:
34     //  1. a consistent size allocation when our estimate is drifting slowly
35     //     (which is common) - which tends to help most allocators reuse memory
36     //  2. a small amount of allowed growth over the estimate without hitting
37     //     the arena size doubling case, reducing overall memory usage
38     static constexpr size_t kRoundUpSize = 256;
39     return (call_size_estimate_.load(std::memory_order_relaxed) +
40             2 * kRoundUpSize) &
41            ~(kRoundUpSize - 1);
42   }
43 
44   void UpdateCallSizeEstimate(size_t size);
45 
46  private:
47   std::atomic<size_t> call_size_estimate_;
48 };
49 
50 }  // namespace grpc_core
51 
52 #endif  // GRPC_SRC_CORE_LIB_TRANSPORT_CALL_SIZE_ESTIMATOR_H
53