perf: math: precompute & use square of precisionReuse instead of 2 repeated computations (#12794)
This commit is contained in:
parent
cb31043d35
commit
f002e54d26
13
math/dec.go
13
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)
|
||||
|
||||
@ -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)
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user