From f002e54d2679e02ed31278a3e925e4f20f3aaa1d Mon Sep 17 00:00:00 2001 From: Emmanuel T Odeke Date: Tue, 2 Aug 2022 07:00:08 -0700 Subject: [PATCH] perf: math: precompute & use square of precisionReuse instead of 2 repeated computations (#12794) --- math/dec.go | 13 ++++++------- math/dec_test.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/math/dec.go b/math/dec.go index 667bfec50b..90bb8c7ace 100644 --- a/math/dec.go +++ b/math/dec.go @@ -342,11 +342,12 @@ func (d LegacyDec) Quo(d2 LegacyDec) LegacyDec { return d.ImmutOp(LegacyDec.QuoMut, d2) } +var squaredPrecisionReuse = new(big.Int).Mul(precisionReuse, precisionReuse) + // mutable quotient func (d LegacyDec) QuoMut(d2 LegacyDec) LegacyDec { - // multiply precision twice - d.i.Mul(d.i, precisionReuse) - d.i.Mul(d.i, precisionReuse) + // multiply by precision twice + d.i.Mul(d.i, squaredPrecisionReuse) d.i.Quo(d.i, d2.i) chopPrecisionAndRound(d.i) @@ -364,8 +365,7 @@ func (d LegacyDec) QuoTruncate(d2 LegacyDec) LegacyDec { // mutable quotient truncate func (d LegacyDec) QuoTruncateMut(d2 LegacyDec) LegacyDec { // multiply precision twice - d.i.Mul(d.i, precisionReuse) - d.i.Mul(d.i, precisionReuse) + d.i.Mul(d.i, squaredPrecisionReuse) d.i.Quo(d.i, d2.i) chopPrecisionAndTruncate(d.i) @@ -383,8 +383,7 @@ func (d LegacyDec) QuoRoundUp(d2 LegacyDec) LegacyDec { // mutable quotient, round up func (d LegacyDec) QuoRoundupMut(d2 LegacyDec) LegacyDec { // multiply precision twice - d.i.Mul(d.i, precisionReuse) - d.i.Mul(d.i, precisionReuse) + d.i.Mul(d.i, squaredPrecisionReuse) d.i.Quo(d.i, d2.i) chopPrecisionAndRoundUp(d.i) diff --git a/math/dec_test.go b/math/dec_test.go index d390d45201..637ef71ee0 100644 --- a/math/dec_test.go +++ b/math/dec_test.go @@ -619,3 +619,50 @@ func BenchmarkMarshalTo(b *testing.B) { } } } + +var sink interface{} + +func BenchmarkLegacyQuoMut(b *testing.B) { + b1 := math.LegacyNewDec(17e2 + 8371) + b2 := math.LegacyNewDec(4371) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + sink = b1.QuoMut(b2) + } + + if sink == nil { + b.Fatal("Benchmark did not run") + } + sink = (interface{})(nil) +} + +func BenchmarkLegacyQuoTruncateMut(b *testing.B) { + b1 := math.LegacyNewDec(17e2 + 8371) + b2 := math.LegacyNewDec(4371) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + sink = b1.QuoTruncateMut(b2) + } + + if sink == nil { + b.Fatal("Benchmark did not run") + } + sink = (interface{})(nil) +} + +func BenchmarkLegacyQuoRoundupMut(b *testing.B) { + b1 := math.LegacyNewDec(17e2 + 8371) + b2 := math.LegacyNewDec(4371) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + sink = b1.QuoRoundupMut(b2) + } + + if sink == nil { + b.Fatal("Benchmark did not run") + } + sink = (interface{})(nil) +}