Created
October 2, 2020 21:19
-
-
Save dolinenkov/80573f6ada68af4a6523ab11f4b77e5d to your computer and use it in GitHub Desktop.
Scalable value statistics wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <algorithm> | |
/* | |
* Convenient and scalable value statistics wrapper | |
*/ | |
template<typename T> | |
struct Statistics | |
{ | |
T min = {}; | |
T max = {}; | |
T avg = {}; | |
T rms = {}; | |
size_t count = 0; | |
void merge(Statistics another) | |
{ | |
if (another.count > 0) | |
{ | |
if (count > 0) | |
{ | |
min = std::min(min, another.min); | |
max = std::max(max, another.max); | |
avg = ((avg * count) + (another.avg * another.count)) / (count + another.count); | |
rms = static_cast<T>(sqrt(((rms * rms * count) + (another.rms * another.rms * another.count)) / (count + another.count))); | |
count += another.count; | |
} | |
else | |
{ | |
*this = std::move(another); | |
} | |
} | |
} | |
void update(T v) | |
{ | |
merge(Statistics{ v, v, v, v, 1 }); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment