Skip to content

Commit

Permalink
optimize + benchmark muloverflow (#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
holiman authored Jun 5, 2020
1 parent ccc827b commit beb0847
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
28 changes: 28 additions & 0 deletions benchmarks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,34 @@ func BenchmarkMul(bench *testing.B) {
bench.Run("single/big", benchmarkBig)
}

func BenchmarkMulOverflow(bench *testing.B) {
benchmarkUint256 := func(bench *testing.B) {
a := big.NewInt(0).SetBytes(hex2Bytes("f123456789abcdeffedcba9876543210f2f3f4f5f6f7f8f9fff3f4f5f6f7f8f9"))
b := big.NewInt(0).SetBytes(hex2Bytes("f123456789abcdefaaaaaa9876543210f2f3f4f5f6f7f8f9fff3f4f5f6f7f8f9"))
fa, _ := FromBig(a)
fb, _ := FromBig(b)

result := new(Int)
bench.ResetTimer()
for i := 0; i < bench.N; i++ {
result.MulOverflow(fa, fb)
}
}
benchmarkBig := func(bench *testing.B) {
a := new(big.Int).SetBytes(hex2Bytes("f123456789abcdeffedcba9876543210f2f3f4f5f6f7f8f9fff3f4f5f6f7f8f9"))
b := new(big.Int).SetBytes(hex2Bytes("f123456789abcdefaaaaaa9876543210f2f3f4f5f6f7f8f9fff3f4f5f6f7f8f9"))

result := new(big.Int)
bench.ResetTimer()
for i := 0; i < bench.N; i++ {
U256(result.Mul(a, b))
}
}

bench.Run("single/uint256", benchmarkUint256)
bench.Run("single/big", benchmarkBig)
}

func BenchmarkSquare(bench *testing.B) {

benchmarkUint256 := func(bench *testing.B) {
Expand Down
11 changes: 2 additions & 9 deletions uint256.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,15 +330,8 @@ func (z *Int) Mul(x, y *Int) *Int {
// MulOverflow sets z to the product x*y, and returns whether overflow occurred
func (z *Int) MulOverflow(x, y *Int) bool {
p := umul(x, y)
var (
pl Int
ph Int
)
copy(pl[:], p[:4])
copy(ph[:], p[4:])

z.Set(&pl)
return !ph.IsZero()
copy(z[:], p[:4])
return (p[4] | p[5] | p[6] | p[7]) != 0
}

func (z *Int) squared() {
Expand Down

0 comments on commit beb0847

Please sign in to comment.