time_averaged_stats.cc 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #include <grpc/support/port_platform.h>
  19. #include "src/core/lib/iomgr/time_averaged_stats.h"
  20. void grpc_time_averaged_stats_init(grpc_time_averaged_stats* stats,
  21. double init_avg, double regress_weight,
  22. double persistence_factor) {
  23. stats->init_avg = init_avg;
  24. stats->regress_weight = regress_weight;
  25. stats->persistence_factor = persistence_factor;
  26. stats->batch_total_value = 0;
  27. stats->batch_num_samples = 0;
  28. stats->aggregate_total_weight = 0;
  29. stats->aggregate_weighted_avg = init_avg;
  30. }
  31. void grpc_time_averaged_stats_add_sample(grpc_time_averaged_stats* stats,
  32. double value) {
  33. stats->batch_total_value += value;
  34. ++stats->batch_num_samples;
  35. }
  36. double grpc_time_averaged_stats_update_average(
  37. grpc_time_averaged_stats* stats) {
  38. /* Start with the current batch: */
  39. double weighted_sum = stats->batch_total_value;
  40. double total_weight = stats->batch_num_samples;
  41. if (stats->regress_weight > 0) {
  42. /* Add in the regression towards init_avg_: */
  43. weighted_sum += stats->regress_weight * stats->init_avg;
  44. total_weight += stats->regress_weight;
  45. }
  46. if (stats->persistence_factor > 0) {
  47. /* Add in the persistence: */
  48. const double prev_sample_weight =
  49. stats->persistence_factor * stats->aggregate_total_weight;
  50. weighted_sum += prev_sample_weight * stats->aggregate_weighted_avg;
  51. total_weight += prev_sample_weight;
  52. }
  53. stats->aggregate_weighted_avg =
  54. (total_weight > 0) ? (weighted_sum / total_weight) : stats->init_avg;
  55. stats->aggregate_total_weight = total_weight;
  56. stats->batch_num_samples = 0;
  57. stats->batch_total_value = 0;
  58. return stats->aggregate_weighted_avg;
  59. }