incremental_sum.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #ifndef NETDATA_API_QUERY_INCREMENTAL_SUM_H
  3. #define NETDATA_API_QUERY_INCREMENTAL_SUM_H
  4. #include "../query.h"
  5. #include "../rrdr.h"
  6. struct tg_incremental_sum {
  7. NETDATA_DOUBLE first;
  8. NETDATA_DOUBLE last;
  9. size_t count;
  10. };
  11. static inline void tg_incremental_sum_create(RRDR *r, const char *options __maybe_unused) {
  12. r->time_grouping.data = onewayalloc_callocz(r->internal.owa, 1, sizeof(struct tg_incremental_sum));
  13. }
  14. // resets when switches dimensions
  15. // so, clear everything to restart
  16. static inline void tg_incremental_sum_reset(RRDR *r) {
  17. struct tg_incremental_sum *g = (struct tg_incremental_sum *)r->time_grouping.data;
  18. g->first = 0;
  19. g->last = 0;
  20. g->count = 0;
  21. }
  22. static inline void tg_incremental_sum_free(RRDR *r) {
  23. onewayalloc_freez(r->internal.owa, r->time_grouping.data);
  24. r->time_grouping.data = NULL;
  25. }
  26. static inline void tg_incremental_sum_add(RRDR *r, NETDATA_DOUBLE value) {
  27. struct tg_incremental_sum *g = (struct tg_incremental_sum *)r->time_grouping.data;
  28. if(unlikely(!g->count)) {
  29. g->first = value;
  30. g->count++;
  31. }
  32. else {
  33. g->last = value;
  34. g->count++;
  35. }
  36. }
  37. static inline NETDATA_DOUBLE tg_incremental_sum_flush(RRDR *r, RRDR_VALUE_FLAGS *rrdr_value_options_ptr) {
  38. struct tg_incremental_sum *g = (struct tg_incremental_sum *)r->time_grouping.data;
  39. NETDATA_DOUBLE value;
  40. if(unlikely(!g->count)) {
  41. value = 0.0;
  42. *rrdr_value_options_ptr |= RRDR_VALUE_EMPTY;
  43. }
  44. else if(unlikely(g->count == 1)) {
  45. value = 0.0;
  46. }
  47. else {
  48. value = g->last - g->first;
  49. }
  50. g->first = 0.0;
  51. g->last = 0.0;
  52. g->count = 0;
  53. return value;
  54. }
  55. #endif //NETDATA_API_QUERY_INCREMENTAL_SUM_H