From fbae2f7fe95a05954f79c7dd48f3cb3b55ffce8d Mon Sep 17 00:00:00 2001 From: Alan Bernstein Date: Thu, 17 Nov 2016 15:44:19 -0600 Subject: [PATCH] Add standard deviation to stats --- bench/stats.go | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/bench/stats.go b/bench/stats.go index 0c1b027cf..dc8a86328 100644 --- a/bench/stats.go +++ b/bench/stats.go @@ -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 {