go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/mathutil/mean_duration.go (about) 1 /* 2 3 Copyright (c) 2024 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package mathutil 9 10 import ( 11 "math/big" 12 "time" 13 ) 14 15 // MeanDuration returns the mean or average of a list of durations. 16 // 17 // The underlying math is done with the `big` package so it may 18 // be slightly slower than anticipated, but this prevents overflows. 19 func MeanDuration(durations []time.Duration) time.Duration { 20 if len(durations) == 0 { 21 return 0 22 } 23 accum := new(big.Int) 24 for _, d := range durations { 25 accum.Add(accum, big.NewInt(int64(d))) 26 } 27 accum.Div(accum, big.NewInt(int64(len(durations)))) 28 return time.Duration(accum.Int64()) 29 }