From 7b676650bafc7062eac7240b32254562e666a428 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Fri, 8 Dec 2023 14:39:17 -0500
Subject: [PATCH v3 06/12] Add accumulator to calculate normal dist online

Add PgStat_Accumulator which tracks the information required to
calculate a mean and standard deviation online. This is useful for
storing stats whose values are normally distributed.
---
 src/include/pgstat.h             | 64 ++++++++++++++++++++++++++++++++
 src/tools/pgindent/typedefs.list |  1 +
 2 files changed, 65 insertions(+)

diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index dd914e606eb..e5cceb0237b 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -11,6 +11,8 @@
 #ifndef PGSTAT_H
 #define PGSTAT_H
 
+#include <math.h>
+
 #include "access/xlogdefs.h"
 #include "datatype/timestamp.h"
 #include "portability/instr_time.h"
@@ -138,6 +140,68 @@ typedef struct PgStat_BackendSubEntry
 	PgStat_Counter sync_error_count;
 } PgStat_BackendSubEntry;
 
+/*
+ * Used both in backend local and shared memory, this accumulator keeps track of
+ * the counters needed to calculate a mean and standard deviation online.
+ */
+typedef struct PgStat_Accumulator
+{
+	/* Number of values in this accumulator */
+	uint64		n;
+
+	/* Sum of values */
+	double		s;
+
+	/* Sum of squared values */
+	double		q;
+} PgStat_Accumulator;
+
+static inline void
+accumulator_insert(PgStat_Accumulator *accumulator, double v)
+{
+	accumulator->n++;
+	accumulator->s += v;
+	accumulator->q += pow(v, 2);
+}
+
+static inline double
+accumulator_remove(PgStat_Accumulator *accumulator)
+{
+	double		result;
+
+	Assert(accumulator->n > 0);
+
+	result = accumulator->s / accumulator->n;
+
+	accumulator->n--;
+	accumulator->s -= result;
+	accumulator->q -= pow(result, 2);
+
+	return result;
+}
+
+static inline void
+accumulator_absorb(PgStat_Accumulator *target, PgStat_Accumulator *source)
+{
+	target->n += source->n;
+	target->s += source->s;
+	target->q += source->q;
+}
+
+static inline void
+accumulator_calculate(PgStat_Accumulator *accumulator, double *mean,
+					  double *stddev)
+{
+	*mean = NAN;
+	*stddev = INFINITY;
+
+	if (accumulator->n == 0)
+		return;
+
+	*mean = accumulator->s / accumulator->n;
+	*stddev = sqrt((accumulator->q - pow(accumulator->s, 2) / accumulator->n) / accumulator->n);
+}
+
 /* ----------
  * PgStat_TableCounts			The actual per-table counts kept by a backend
  *
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 49014d0367e..cf8086616b2 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2058,6 +2058,7 @@ PgStatShared_ReplSlot
 PgStatShared_SLRU
 PgStatShared_Subscription
 PgStatShared_Wal
+PgStat_Accumulator
 PgStat_ArchiverStats
 PgStat_BackendSubEntry
 PgStat_BgWriterStats
-- 
2.37.2

