perf: math: precompute & use square of precisionReuse instead of 2 repeated computations (#12794)

This commit is contained in:
Emmanuel T Odeke 2022-08-02 07:00:08 -07:00 committed by GitHub
parent cb31043d35
commit f002e54d26
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 7 deletions

View File

@ -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)

View File

@ -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)
}