1 //
2 //
3 // Copyright 2015 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include <grpc/support/port_platform.h>
20 
21 #include "src/core/lib/gprpp/time_averaged_stats.h"
22 
23 namespace grpc_core {
24 
TimeAveragedStats(double init_avg,double regress_weight,double persistence_factor)25 TimeAveragedStats::TimeAveragedStats(double init_avg, double regress_weight,
26                                      double persistence_factor)
27     : init_avg_(init_avg),
28       regress_weight_(regress_weight),
29       persistence_factor_(persistence_factor) {}
30 
AddSample(double value)31 void TimeAveragedStats::AddSample(double value) {
32   batch_total_value_ += value;
33   ++batch_num_samples_;
34 }
35 
UpdateAverage()36 double TimeAveragedStats::UpdateAverage() {
37   // Start with the current batch:
38   double weighted_sum = batch_total_value_;
39   double total_weight = batch_num_samples_;
40   if (regress_weight_ > 0) {
41     // Add in the regression towards init_avg_:
42     weighted_sum += regress_weight_ * init_avg_;
43     total_weight += regress_weight_;
44   }
45   if (persistence_factor_ > 0) {
46     // Add in the persistence:
47     const double prev_sample_weight =
48         persistence_factor_ * aggregate_total_weight_;
49     weighted_sum += prev_sample_weight * aggregate_weighted_avg_;
50     total_weight += prev_sample_weight;
51   }
52   aggregate_weighted_avg_ =
53       (total_weight > 0) ? (weighted_sum / total_weight) : init_avg_;
54   aggregate_total_weight_ = total_weight;
55   batch_num_samples_ = 0;
56   batch_total_value_ = 0;
57   return aggregate_weighted_avg_;
58 }
59 
60 }  // namespace grpc_core
61