@@ -22,6 +22,7 @@ import (
22
22
"errors"
23
23
"fmt"
24
24
"io/ioutil"
25
+ "math/big"
25
26
"math/rand"
26
27
"os"
27
28
"reflect"
@@ -30,7 +31,9 @@ import (
30
31
31
32
"github.com/davecgh/go-spew/spew"
32
33
"github.com/ethereum/go-ethereum/common"
34
+ "github.com/ethereum/go-ethereum/crypto"
33
35
"github.com/ethereum/go-ethereum/ethdb"
36
+ "github.com/ethereum/go-ethereum/rlp"
34
37
)
35
38
36
39
func init () {
@@ -505,8 +508,6 @@ func BenchmarkGet(b *testing.B) { benchGet(b, false) }
505
508
func BenchmarkGetDB (b * testing.B ) { benchGet (b , true ) }
506
509
func BenchmarkUpdateBE (b * testing.B ) { benchUpdate (b , binary .BigEndian ) }
507
510
func BenchmarkUpdateLE (b * testing.B ) { benchUpdate (b , binary .LittleEndian ) }
508
- func BenchmarkHashBE (b * testing.B ) { benchHash (b , binary .BigEndian ) }
509
- func BenchmarkHashLE (b * testing.B ) { benchHash (b , binary .LittleEndian ) }
510
511
511
512
const benchElemCount = 20000
512
513
@@ -549,18 +550,39 @@ func benchUpdate(b *testing.B, e binary.ByteOrder) *Trie {
549
550
return trie
550
551
}
551
552
552
- func benchHash (b * testing.B , e binary.ByteOrder ) {
553
+ // Benchmarks the trie hashing. Since the trie caches the result of any operation,
554
+ // we cannot use b.N as the number of hashing rouns, since all rounds apart from
555
+ // the first one will be NOOP. As such, we'll use b.N as the number of account to
556
+ // insert into the trie before measuring the hashing.
557
+ func BenchmarkHash (b * testing.B ) {
558
+ // Make the random benchmark deterministic
559
+ random := rand .New (rand .NewSource (0 ))
560
+
561
+ // Create a realistic account trie to hash
562
+ addresses := make ([][20 ]byte , b .N )
563
+ for i := 0 ; i < len (addresses ); i ++ {
564
+ for j := 0 ; j < len (addresses [i ]); j ++ {
565
+ addresses [i ][j ] = byte (random .Intn (256 ))
566
+ }
567
+ }
568
+ accounts := make ([][]byte , len (addresses ))
569
+ for i := 0 ; i < len (accounts ); i ++ {
570
+ var (
571
+ nonce = uint64 (random .Int63 ())
572
+ balance = new (big.Int ).Rand (random , new (big.Int ).Exp (common .Big2 , common .Big256 , nil ))
573
+ root = emptyRoot
574
+ code = crypto .Keccak256 (nil )
575
+ )
576
+ accounts [i ], _ = rlp .EncodeToBytes ([]interface {}{nonce , balance , root , code })
577
+ }
578
+ // Insert the accounts into the trie and hash it
553
579
trie := newEmpty ()
554
- k := make ([]byte , 32 )
555
- for i := 0 ; i < benchElemCount ; i ++ {
556
- e .PutUint64 (k , uint64 (i ))
557
- trie .Update (k , k )
580
+ for i := 0 ; i < len (addresses ); i ++ {
581
+ trie .Update (crypto .Keccak256 (addresses [i ][:]), accounts [i ])
558
582
}
559
-
560
583
b .ResetTimer ()
561
- for i := 0 ; i < b .N ; i ++ {
562
- trie .Hash ()
563
- }
584
+ b .ReportAllocs ()
585
+ trie .Hash ()
564
586
}
565
587
566
588
func tempDB () (string , Database ) {
0 commit comments