From fbae2f7fe95a05954f79c7dd48f3cb3b55ffce8d Mon Sep 17 00:00:00 2001 From: Alan Bernstein Date: Thu, 17 Nov 2016 15:44:19 -0600 Subject: [PATCH 1/2] 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 { From ff8766126803203c74b0b75fe7e019743790fe15 Mon Sep 17 00:00:00 2001 From: Alan Bernstein Date: Fri, 18 Nov 2016 09:33:48 -0600 Subject: [PATCH 2/2] Move sqrt out of Add() --- bench/stats.go | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/bench/stats.go b/bench/stats.go index dc8a86328..cb4395c13 100644 --- a/bench/stats.go +++ b/bench/stats.go @@ -9,9 +9,7 @@ type Stats struct { Min time.Duration Max time.Duration Mean time.Duration - SumSquareDelta float64 - Variance float64 - StdDev time.Duration + sumSquareDelta float64 Total time.Duration Num int64 } @@ -32,15 +30,11 @@ func (s *Stats) Add(td time.Duration) { s.Max = td } - // these three comprise an online variance calculation + // 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)) + s.sumSquareDelta += float64(delta * (td - s.Mean)) } func (s *Stats) Avg() time.Duration { @@ -50,5 +44,7 @@ func (s *Stats) Avg() time.Duration { func AddToResults(s *Stats, results map[string]interface{}) { results["min"] = s.Min results["max"] = s.Max - results["avg"] = s.Avg() + results["avg"] = s.Mean + variance := s.sumSquareDelta / float64(s.Num) + results["std"] = time.Duration(math.Sqrt(variance)) }