| 32 | |
| 33 | template <typename ValueType, typename HighPrecisionValueType = double> |
| 34 | class Stat { |
| 35 | public: |
| 36 | void UpdateStat(ValueType v) { |
| 37 | if (count_ == 0) { |
| 38 | first_ = v; |
| 39 | } |
| 40 | |
| 41 | newest_ = v; |
| 42 | max_ = std::max(v, max_); |
| 43 | min_ = std::min(v, min_); |
| 44 | ++count_; |
| 45 | sum_ += v; |
| 46 | squared_sum_ += static_cast<HighPrecisionValueType>(v) * v; |
| 47 | } |
| 48 | |
| 49 | void Reset() { new (this) Stat<ValueType, HighPrecisionValueType>(); } |
| 50 | |
| 51 | bool empty() const { return count_ == 0; } |
| 52 | |
| 53 | ValueType first() const { return first_; } |
| 54 | |
| 55 | ValueType newest() const { return newest_; } |
| 56 | |
| 57 | ValueType max() const { return max_; } |
| 58 | |
| 59 | ValueType min() const { return min_; } |
| 60 | |
| 61 | int64_t count() const { return count_; } |
| 62 | |
| 63 | ValueType sum() const { return sum_; } |
| 64 | |
| 65 | HighPrecisionValueType squared_sum() const { return squared_sum_; } |
| 66 | |
| 67 | bool all_same() const { return (count_ == 0 || min_ == max_); } |
| 68 | |
| 69 | HighPrecisionValueType avg() const { |
| 70 | return empty() ? std::numeric_limits<ValueType>::quiet_NaN() |
| 71 | : static_cast<HighPrecisionValueType>(sum_) / count_; |
| 72 | } |
| 73 | |
| 74 | ValueType std_deviation() const { |
| 75 | return all_same() ? 0 : sqrt(squared_sum_ / count_ - avg() * avg()); |
| 76 | } |
| 77 | |
| 78 | void OutputToStream(std::ostream* stream) const { |
| 79 | if (empty()) { |
| 80 | *stream << "count=0"; |
| 81 | } else if (all_same()) { |
| 82 | *stream << "count=" << count_ << " curr=" << newest_; |
| 83 | if (count_ > 1) *stream << "(all same)"; |
| 84 | } else { |
| 85 | *stream << "count=" << count_ << " first=" << first_ |
| 86 | << " curr=" << newest_ << " min=" << min_ << " max=" << max_ |
| 87 | << " avg=" << avg() << " std=" << std_deviation(); |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | friend std::ostream& operator<<(std::ostream& stream, |
no test coverage detected