From c8b5fd4aa5e5b97454a48efb53c040083e25aeaf Mon Sep 17 00:00:00 2001 From: Ralph Caraveo Date: Thu, 5 Apr 2018 10:27:22 -0700 Subject: [PATCH] Update gauge_float64.go to reduce lock contention --- gauge_float64.go | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/gauge_float64.go b/gauge_float64.go index 6f93920..3962e6d 100644 --- a/gauge_float64.go +++ b/gauge_float64.go @@ -1,6 +1,9 @@ package metrics -import "sync" +import ( + "math" + "sync/atomic" +) // GaugeFloat64s hold a float64 value that can be set arbitrarily. type GaugeFloat64 interface { @@ -85,8 +88,7 @@ func (NilGaugeFloat64) Value() float64 { return 0.0 } // StandardGaugeFloat64 is the standard implementation of a GaugeFloat64 and uses // sync.Mutex to manage a single float64 value. type StandardGaugeFloat64 struct { - mutex sync.Mutex - value float64 + value uint64 } // Snapshot returns a read-only copy of the gauge. @@ -96,16 +98,12 @@ func (g *StandardGaugeFloat64) Snapshot() GaugeFloat64 { // Update updates the gauge's value. func (g *StandardGaugeFloat64) Update(v float64) { - g.mutex.Lock() - defer g.mutex.Unlock() - g.value = v + atomic.StoreUint64(&g.value, math.Float64bits(v)) } // Value returns the gauge's current value. func (g *StandardGaugeFloat64) Value() float64 { - g.mutex.Lock() - defer g.mutex.Unlock() - return g.value + return math.Float64frombits(atomic.LoadUint64(&g.value)) } // FunctionalGaugeFloat64 returns value from given function