metrics: Use N_EWMA for moving avg, with N=100.
[tor.git] / src / lib / math / stats.h
blob14315a2506aea5fb3f7d770dfb7846b627c78f69
1 /* Copyright (c) 2022, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file stats.h
7 * \brief Header for stats.c
8 **/
10 #ifndef TOR_STATS_H
11 #define TOR_STATS_H
13 /**
14 * Compute an N-count EWMA, aka N-EWMA. N-EWMA is defined as:
15 * EWMA = alpha*value + (1-alpha)*EWMA_prev
16 * with alpha = 2/(N+1).
18 * This works out to:
19 * EWMA = value*2/(N+1) + EMA_prev*(N-1)/(N+1)
20 * = (value*2 + EWMA_prev*(N-1))/(N+1)
22 static inline double
23 n_count_ewma_double(double avg, double value, uint64_t N)
25 /* If the average was not previously computed, return value.
26 * The less than is because we have stupid C warning flags that
27 * prevent exact comparison to 0.0, so we can't do an exact
28 * check for unitialized double values. Yay pedantry!
29 * Love it when it introduces surprising edge case bugs like
30 * this will. */
31 if (avg < 0.0000002)
32 return value;
33 else
34 return (2*value + (N-1)*avg)/(N+1);
37 /* For most stats, an N_EWMA of 100 is sufficient */
38 #define DEFAULT_STATS_N_EWMA_COUNT 100
39 #define stats_update_running_avg(avg, value) \
40 n_count_ewma_double(avg, value, DEFAULT_STATS_N_EWMA_COUNT)
42 #endif /* !defined(TOR_STATS_H) */