github.com/ylsGit/go-ethereum@v1.6.5/core/bench_test.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"io/ioutil"
    22  	"math/big"
    23  	"os"
    24  	"testing"
    25  
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/common/math"
    28  	"github.com/ethereum/go-ethereum/consensus/ethash"
    29  	"github.com/ethereum/go-ethereum/core/types"
    30  	"github.com/ethereum/go-ethereum/core/vm"
    31  	"github.com/ethereum/go-ethereum/crypto"
    32  	"github.com/ethereum/go-ethereum/ethdb"
    33  	"github.com/ethereum/go-ethereum/event"
    34  	"github.com/ethereum/go-ethereum/params"
    35  )
    36  
    37  func BenchmarkInsertChain_empty_memdb(b *testing.B) {
    38  	benchInsertChain(b, false, nil)
    39  }
    40  func BenchmarkInsertChain_empty_diskdb(b *testing.B) {
    41  	benchInsertChain(b, true, nil)
    42  }
    43  func BenchmarkInsertChain_valueTx_memdb(b *testing.B) {
    44  	benchInsertChain(b, false, genValueTx(0))
    45  }
    46  func BenchmarkInsertChain_valueTx_diskdb(b *testing.B) {
    47  	benchInsertChain(b, true, genValueTx(0))
    48  }
    49  func BenchmarkInsertChain_valueTx_100kB_memdb(b *testing.B) {
    50  	benchInsertChain(b, false, genValueTx(100*1024))
    51  }
    52  func BenchmarkInsertChain_valueTx_100kB_diskdb(b *testing.B) {
    53  	benchInsertChain(b, true, genValueTx(100*1024))
    54  }
    55  func BenchmarkInsertChain_uncles_memdb(b *testing.B) {
    56  	benchInsertChain(b, false, genUncles)
    57  }
    58  func BenchmarkInsertChain_uncles_diskdb(b *testing.B) {
    59  	benchInsertChain(b, true, genUncles)
    60  }
    61  func BenchmarkInsertChain_ring200_memdb(b *testing.B) {
    62  	benchInsertChain(b, false, genTxRing(200))
    63  }
    64  func BenchmarkInsertChain_ring200_diskdb(b *testing.B) {
    65  	benchInsertChain(b, true, genTxRing(200))
    66  }
    67  func BenchmarkInsertChain_ring1000_memdb(b *testing.B) {
    68  	benchInsertChain(b, false, genTxRing(1000))
    69  }
    70  func BenchmarkInsertChain_ring1000_diskdb(b *testing.B) {
    71  	benchInsertChain(b, true, genTxRing(1000))
    72  }
    73  
    74  var (
    75  	// This is the content of the genesis block used by the benchmarks.
    76  	benchRootKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    77  	benchRootAddr   = crypto.PubkeyToAddress(benchRootKey.PublicKey)
    78  	benchRootFunds  = math.BigPow(2, 100)
    79  )
    80  
    81  // genValueTx returns a block generator that includes a single
    82  // value-transfer transaction with n bytes of extra data in each
    83  // block.
    84  func genValueTx(nbytes int) func(int, *BlockGen) {
    85  	return func(i int, gen *BlockGen) {
    86  		toaddr := common.Address{}
    87  		data := make([]byte, nbytes)
    88  		gas := IntrinsicGas(data, false, false)
    89  		tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(benchRootAddr), toaddr, big.NewInt(1), gas, nil, data), types.HomesteadSigner{}, benchRootKey)
    90  		gen.AddTx(tx)
    91  	}
    92  }
    93  
    94  var (
    95  	ringKeys  = make([]*ecdsa.PrivateKey, 1000)
    96  	ringAddrs = make([]common.Address, len(ringKeys))
    97  	bigTxGas  = new(big.Int).SetUint64(params.TxGas)
    98  )
    99  
   100  func init() {
   101  	ringKeys[0] = benchRootKey
   102  	ringAddrs[0] = benchRootAddr
   103  	for i := 1; i < len(ringKeys); i++ {
   104  		ringKeys[i], _ = crypto.GenerateKey()
   105  		ringAddrs[i] = crypto.PubkeyToAddress(ringKeys[i].PublicKey)
   106  	}
   107  }
   108  
   109  // genTxRing returns a block generator that sends ether in a ring
   110  // among n accounts. This is creates n entries in the state database
   111  // and fills the blocks with many small transactions.
   112  func genTxRing(naccounts int) func(int, *BlockGen) {
   113  	from := 0
   114  	return func(i int, gen *BlockGen) {
   115  		gas := CalcGasLimit(gen.PrevBlock(i - 1))
   116  		for {
   117  			gas.Sub(gas, bigTxGas)
   118  			if gas.Cmp(bigTxGas) < 0 {
   119  				break
   120  			}
   121  			to := (from + 1) % naccounts
   122  			tx := types.NewTransaction(
   123  				gen.TxNonce(ringAddrs[from]),
   124  				ringAddrs[to],
   125  				benchRootFunds,
   126  				bigTxGas,
   127  				nil,
   128  				nil,
   129  			)
   130  			tx, _ = types.SignTx(tx, types.HomesteadSigner{}, ringKeys[from])
   131  			gen.AddTx(tx)
   132  			from = to
   133  		}
   134  	}
   135  }
   136  
   137  // genUncles generates blocks with two uncle headers.
   138  func genUncles(i int, gen *BlockGen) {
   139  	if i >= 6 {
   140  		b2 := gen.PrevBlock(i - 6).Header()
   141  		b2.Extra = []byte("foo")
   142  		gen.AddUncle(b2)
   143  		b3 := gen.PrevBlock(i - 6).Header()
   144  		b3.Extra = []byte("bar")
   145  		gen.AddUncle(b3)
   146  	}
   147  }
   148  
   149  func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) {
   150  	// Create the database in memory or in a temporary directory.
   151  	var db ethdb.Database
   152  	if !disk {
   153  		db, _ = ethdb.NewMemDatabase()
   154  	} else {
   155  		dir, err := ioutil.TempDir("", "eth-core-bench")
   156  		if err != nil {
   157  			b.Fatalf("cannot create temporary directory: %v", err)
   158  		}
   159  		defer os.RemoveAll(dir)
   160  		db, err = ethdb.NewLDBDatabase(dir, 128, 128)
   161  		if err != nil {
   162  			b.Fatalf("cannot create temporary database: %v", err)
   163  		}
   164  		defer db.Close()
   165  	}
   166  
   167  	// Generate a chain of b.N blocks using the supplied block
   168  	// generator function.
   169  	gspec := Genesis{
   170  		Config: params.TestChainConfig,
   171  		Alloc:  GenesisAlloc{benchRootAddr: {Balance: benchRootFunds}},
   172  	}
   173  	genesis := gspec.MustCommit(db)
   174  	chain, _ := GenerateChain(gspec.Config, genesis, db, b.N, gen)
   175  
   176  	// Time the insertion of the new chain.
   177  	// State and blocks are stored in the same DB.
   178  	evmux := new(event.TypeMux)
   179  	chainman, _ := NewBlockChain(db, gspec.Config, ethash.NewFaker(), evmux, vm.Config{})
   180  	defer chainman.Stop()
   181  	b.ReportAllocs()
   182  	b.ResetTimer()
   183  	if i, err := chainman.InsertChain(chain); err != nil {
   184  		b.Fatalf("insert error (block %d): %v\n", i, err)
   185  	}
   186  }
   187  
   188  func BenchmarkChainRead_header_10k(b *testing.B) {
   189  	benchReadChain(b, false, 10000)
   190  }
   191  func BenchmarkChainRead_full_10k(b *testing.B) {
   192  	benchReadChain(b, true, 10000)
   193  }
   194  func BenchmarkChainRead_header_100k(b *testing.B) {
   195  	benchReadChain(b, false, 100000)
   196  }
   197  func BenchmarkChainRead_full_100k(b *testing.B) {
   198  	benchReadChain(b, true, 100000)
   199  }
   200  func BenchmarkChainRead_header_500k(b *testing.B) {
   201  	benchReadChain(b, false, 500000)
   202  }
   203  func BenchmarkChainRead_full_500k(b *testing.B) {
   204  	benchReadChain(b, true, 500000)
   205  }
   206  func BenchmarkChainWrite_header_10k(b *testing.B) {
   207  	benchWriteChain(b, false, 10000)
   208  }
   209  func BenchmarkChainWrite_full_10k(b *testing.B) {
   210  	benchWriteChain(b, true, 10000)
   211  }
   212  func BenchmarkChainWrite_header_100k(b *testing.B) {
   213  	benchWriteChain(b, false, 100000)
   214  }
   215  func BenchmarkChainWrite_full_100k(b *testing.B) {
   216  	benchWriteChain(b, true, 100000)
   217  }
   218  func BenchmarkChainWrite_header_500k(b *testing.B) {
   219  	benchWriteChain(b, false, 500000)
   220  }
   221  func BenchmarkChainWrite_full_500k(b *testing.B) {
   222  	benchWriteChain(b, true, 500000)
   223  }
   224  
   225  // makeChainForBench writes a given number of headers or empty blocks/receipts
   226  // into a database.
   227  func makeChainForBench(db ethdb.Database, full bool, count uint64) {
   228  	var hash common.Hash
   229  	for n := uint64(0); n < count; n++ {
   230  		header := &types.Header{
   231  			Coinbase:    common.Address{},
   232  			Number:      big.NewInt(int64(n)),
   233  			ParentHash:  hash,
   234  			Difficulty:  big.NewInt(1),
   235  			UncleHash:   types.EmptyUncleHash,
   236  			TxHash:      types.EmptyRootHash,
   237  			ReceiptHash: types.EmptyRootHash,
   238  		}
   239  		hash = header.Hash()
   240  		WriteHeader(db, header)
   241  		WriteCanonicalHash(db, hash, n)
   242  		WriteTd(db, hash, n, big.NewInt(int64(n+1)))
   243  		if full || n == 0 {
   244  			block := types.NewBlockWithHeader(header)
   245  			WriteBody(db, hash, n, block.Body())
   246  			WriteBlockReceipts(db, hash, n, nil)
   247  		}
   248  	}
   249  }
   250  
   251  func benchWriteChain(b *testing.B, full bool, count uint64) {
   252  	for i := 0; i < b.N; i++ {
   253  		dir, err := ioutil.TempDir("", "eth-chain-bench")
   254  		if err != nil {
   255  			b.Fatalf("cannot create temporary directory: %v", err)
   256  		}
   257  		db, err := ethdb.NewLDBDatabase(dir, 128, 1024)
   258  		if err != nil {
   259  			b.Fatalf("error opening database at %v: %v", dir, err)
   260  		}
   261  		makeChainForBench(db, full, count)
   262  		db.Close()
   263  		os.RemoveAll(dir)
   264  	}
   265  }
   266  
   267  func benchReadChain(b *testing.B, full bool, count uint64) {
   268  	dir, err := ioutil.TempDir("", "eth-chain-bench")
   269  	if err != nil {
   270  		b.Fatalf("cannot create temporary directory: %v", err)
   271  	}
   272  	defer os.RemoveAll(dir)
   273  
   274  	db, err := ethdb.NewLDBDatabase(dir, 128, 1024)
   275  	if err != nil {
   276  		b.Fatalf("error opening database at %v: %v", dir, err)
   277  	}
   278  	makeChainForBench(db, full, count)
   279  	db.Close()
   280  
   281  	b.ReportAllocs()
   282  	b.ResetTimer()
   283  
   284  	for i := 0; i < b.N; i++ {
   285  		db, err := ethdb.NewLDBDatabase(dir, 128, 1024)
   286  		if err != nil {
   287  			b.Fatalf("error opening database at %v: %v", dir, err)
   288  		}
   289  		chain, err := NewBlockChain(db, params.TestChainConfig, ethash.NewFaker(), new(event.TypeMux), vm.Config{})
   290  		if err != nil {
   291  			b.Fatalf("error creating chain: %v", err)
   292  		}
   293  
   294  		for n := uint64(0); n < count; n++ {
   295  			header := chain.GetHeaderByNumber(n)
   296  			if full {
   297  				hash := header.Hash()
   298  				GetBody(db, hash, n)
   299  				GetBlockReceipts(db, hash, n)
   300  			}
   301  		}
   302  
   303  		db.Close()
   304  	}
   305  }