Add standard deviation to stats

This commit is contained in:
Alan Bernstein 2016-11-17 15:44:19 -06:00 committed by jaffee
parent 492df23bde
commit fbae2f7fe9

View file

@ -1,14 +1,19 @@
package bench
import (
"math"
"time"
)
type Stats struct {
Min time.Duration
Max time.Duration
Total time.Duration
Num int64
Min time.Duration
Max time.Duration
Mean time.Duration
SumSquareDelta float64
Variance float64
StdDev time.Duration
Total time.Duration
Num int64
}
func NewStats() *Stats {
@ -26,6 +31,16 @@ func (s *Stats) Add(td time.Duration) {
if td > s.Max {
s.Max = td
}
// these three comprise an online variance calculation
// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm
delta := td - s.Mean
s.Mean += delta / time.Duration(s.Num)
s.SumSquareDelta += float64(delta * (td - s.Mean))
// these are the useful results, but don't need to be updated every iteration
s.Variance = s.SumSquareDelta / float64(s.Num)
s.StdDev = time.Duration(math.Sqrt(s.Variance))
}
func (s *Stats) Avg() time.Duration {