aboutsummaryrefslogtreecommitdiffstats
path: root/src/libutil
diff options
context:
space:
mode:
authorVsevolod Stakhov <vsevolod@highsecure.ru>2018-07-24 19:48:08 +0100
committerVsevolod Stakhov <vsevolod@highsecure.ru>2018-07-24 19:48:08 +0100
commit558bae256922e3c4149fd9798dbd98b04bd5cc55 (patch)
treee67e2fdc03f003aa9d54c80b8f58f69ef247423a /src/libutil
parenta281d6a475ceb0e7553db38a2e74656aed3a8988 (diff)
downloadrspamd-558bae256922e3c4149fd9798dbd98b04bd5cc55.tar.gz
rspamd-558bae256922e3c4149fd9798dbd98b04bd5cc55.zip
[Minor] Place moving average function is generic utilities
Diffstat (limited to 'src/libutil')
-rw-r--r--src/libutil/util.c42
-rw-r--r--src/libutil/util.h26
2 files changed, 67 insertions, 1 deletions
diff --git a/src/libutil/util.c b/src/libutil/util.c
index 93f449791..6554da63b 100644
--- a/src/libutil/util.c
+++ b/src/libutil/util.c
@@ -2973,4 +2973,44 @@ rspamd_glob_path (const gchar *dir,
}
return res;
-} \ No newline at end of file
+}
+
+double
+rspamd_set_counter (struct rspamd_counter_data *cd, gdouble value)
+{
+ gdouble cerr;
+
+ /* Cumulative moving average using per-process counter data */
+ if (cd->number == 0) {
+ cd->mean = 0;
+ cd->stddev = 0;
+ }
+
+ cd->mean += (value - cd->mean) / (gdouble)(++cd->number);
+ cerr = (value - cd->mean) * (value - cd->mean);
+ cd->stddev += (cerr - cd->stddev) / (gdouble)(cd->number);
+
+ return cd->mean;
+}
+
+double
+rspamd_set_counter_ema (struct rspamd_counter_data *cd,
+ gdouble value,
+ gdouble alpha)
+{
+ gdouble diff, incr;
+
+ /* Cumulative moving average using per-process counter data */
+ if (cd->number == 0) {
+ cd->mean = 0;
+ cd->stddev = 0;
+ }
+
+ diff = value - cd->mean;
+ incr = diff * alpha;
+ cd->mean += incr;
+ cd->stddev = (1 - alpha) * (cd->stddev + diff * incr);
+ cd->number ++;
+
+ return cd->mean;
+}
diff --git a/src/libutil/util.h b/src/libutil/util.h
index 5968094a9..4338d5557 100644
--- a/src/libutil/util.h
+++ b/src/libutil/util.h
@@ -511,4 +511,30 @@ GPtrArray *rspamd_glob_path (const gchar *dir,
gboolean recursive,
GError **err);
+struct rspamd_counter_data {
+ gdouble mean;
+ gdouble stddev;
+ guint64 number;
+};
+
+/**
+ * Sets counter's data using exponential moving average
+ * @param cd counter
+ * @param value new counter value
+ * @param alpha decay coefficient (0..1)
+ * @return new counter value
+ */
+double rspamd_set_counter_ema (struct rspamd_counter_data *cd,
+ gdouble value,
+ gdouble alpha);
+
+/**
+ * Sets counter's data using flat moving average
+ * @param cd counter
+ * @param value new counter value
+ * @return new counter value
+ */
+double rspamd_set_counter (struct rspamd_counter_data *cd,
+ gdouble value);
+
#endif