Commit 15ffb9b0 authored by Dave Kurtzberg's avatar Dave Kurtzberg Committed by Facebook GitHub Bot

Add a parameterized ctor and m2 getter

Summary: Allows us to serialized and unserialize StreamingStats.

Reviewed By: yfeldblum

Differential Revision: D30108179

fbshipit-source-id: 7a920acfa10e6c16613e9059049b8550478e81f0
parent 80572dcc
......@@ -37,11 +37,26 @@ class StreamingStats final {
static_assert(std::is_floating_point_v<StatsType>);
public:
struct StreamingState {
size_t count = 0;
StatsType mean = 0;
StatsType m2 = 0;
SampleDataType min = std::numeric_limits<SampleDataType>::max();
SampleDataType max = std::numeric_limits<SampleDataType>::lowest();
};
template <class Iterator>
StreamingStats(Iterator first, Iterator last) noexcept {
add(first, last);
}
explicit StreamingStats(StreamingState state)
: count_(state.count),
mean_(state.mean),
m2_(state.m2),
min_(state.min),
max_(state.max) {}
StreamingStats() = default;
~StreamingStats() = default;
......@@ -104,6 +119,11 @@ class StreamingStats final {
return mean_;
}
StatsType m2() const {
checkMinimumDataSize(1);
return m2_;
}
StatsType populationVariance() const {
checkMinimumDataSize(2);
return var_(0);
......@@ -124,6 +144,16 @@ class StreamingStats final {
return std_(1);
}
StreamingState state() const {
StreamingState state;
state.count = count_;
state.m2 = m2_;
state.max = max_;
state.mean = mean_;
state.min = min_;
return state;
}
private:
void checkMinimumDataSize(size_t const minElements) const {
if (count_ < minElements) {
......
......@@ -43,6 +43,20 @@ TEST(StreamingStatsTest, Constructor) {
EXPECT_DOUBLE_EQ(stats.maximum(), 10.0);
}
TEST(StreamingStatsTest, ConstructFromValues) {
StreamingStats<double> stats1;
for (double i = 0.0; i < 100; i++) {
stats1.add(i);
}
StreamingStats<double> stats2(stats1.state());
EXPECT_EQ(stats1.count(), stats2.count());
EXPECT_EQ(stats1.mean(), stats2.mean());
EXPECT_EQ(stats1.m2(), stats2.m2());
EXPECT_EQ(stats1.minimum(), stats2.minimum());
EXPECT_EQ(stats1.maximum(), stats2.maximum());
}
template <typename SampleDataType>
class StreamingStatsTest : public testing::Test {
public:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment