Skip to content

Commit

Permalink
Significantly speedup quo truncate and quo Roundup
Browse files Browse the repository at this point in the history
  • Loading branch information
ValarDragon committed Apr 13, 2024
1 parent 037cf98 commit 7042594
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
13 changes: 7 additions & 6 deletions math/dec.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,11 +399,10 @@ func (d LegacyDec) QuoTruncate(d2 LegacyDec) LegacyDec {

// QuoTruncateMut mutable quotient truncate
func (d LegacyDec) QuoTruncateMut(d2 LegacyDec) LegacyDec {
// multiply precision twice
d.i.Mul(d.i, squaredPrecisionReuse)
// multiply precision once
d.i.Mul(d.i, precisionReuse)
d.i.Quo(d.i, d2.i)

chopPrecisionAndTruncate(d.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
Expand All @@ -418,10 +417,12 @@ func (d LegacyDec) QuoRoundUp(d2 LegacyDec) LegacyDec {
// QuoRoundupMut mutable quotient, round up
func (d LegacyDec) QuoRoundupMut(d2 LegacyDec) LegacyDec {
// multiply precision twice
d.i.Mul(d.i, squaredPrecisionReuse)
d.i.Quo(d.i, d2.i)
d.i.Mul(d.i, precisionReuse)
_, rem := d.i.QuoRem(d.i, d2.i, big.NewInt(0))
if rem.Sign() != 0 {
d.i.Add(d.i, oneInt)
}

chopPrecisionAndRoundUp(d.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
Expand Down
12 changes: 10 additions & 2 deletions math/dec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -668,11 +668,15 @@ func BenchmarkLegacyQuoMut(b *testing.B) {

func BenchmarkLegacyQuoTruncateMut(b *testing.B) {
b1 := math.LegacyNewDec(17e2 + 8371)
baseArr := make([]math.LegacyDec, b.N)
for i := 0; i < b.N; i++ {
baseArr[i] = b1.Clone()
}
b2 := math.LegacyNewDec(4371)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
sink = b1.QuoTruncateMut(b2)
sink = baseArr[i].QuoTruncateMut(b2)
}

if sink == nil {
Expand All @@ -697,11 +701,15 @@ func BenchmarkLegacySqrtOnMersennePrime(b *testing.B) {

func BenchmarkLegacyQuoRoundupMut(b *testing.B) {
b1 := math.LegacyNewDec(17e2 + 8371)
baseArr := make([]math.LegacyDec, b.N)
for i := 0; i < b.N; i++ {
baseArr[i] = b1.Clone()
}
b2 := math.LegacyNewDec(4371)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
sink = b1.QuoRoundupMut(b2)
sink = baseArr[i].QuoRoundupMut(b2)
}

if sink == nil {
Expand Down

0 comments on commit 7042594

Please sign in to comment.