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