Skip to content

Instantly share code, notes, and snippets.

@dolinenkov
Created October 2, 2020 21:19
Show Gist options
  • Save dolinenkov/80573f6ada68af4a6523ab11f4b77e5d to your computer and use it in GitHub Desktop.
Save dolinenkov/80573f6ada68af4a6523ab11f4b77e5d to your computer and use it in GitHub Desktop.
Scalable value statistics wrapper
#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