From 585ffd6cffff8ed6d1ba6a2a284bf40c7bb32e71 Mon Sep 17 00:00:00 2001 From: Emmanuel T Odeke Date: Tue, 2 Mar 2021 01:01:05 -0800 Subject: [PATCH] x/staking: add ValidateGenesis benchmark (#8746) This benchmark examines how ValidateGenesis behaves. In a follow-up issue, I'll show how it reveals an inefficiency that'll affect trying to load repeatedly retrieve Validators' ConsAddress values. Updates #8744 --- x/staking/bench_test.go | 56 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 x/staking/bench_test.go diff --git a/x/staking/bench_test.go b/x/staking/bench_test.go new file mode 100644 index 000000000000..7705b6d3114f --- /dev/null +++ b/x/staking/bench_test.go @@ -0,0 +1,56 @@ +package staking_test + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" + "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +func BenchmarkValidateGenesis10Validators(b *testing.B) { + benchmarkValidateGenesis(b, 10) +} + +func BenchmarkValidateGenesis100Validators(b *testing.B) { + benchmarkValidateGenesis(b, 100) +} + +func BenchmarkValidateGenesis400Validators(b *testing.B) { + benchmarkValidateGenesis(b, 400) +} + +func benchmarkValidateGenesis(b *testing.B, n int) { + b.ReportAllocs() + + validators := make([]types.Validator, 0, n) + addressL, pubKeyL := makeRandomAddressesAndPublicKeys(n) + for i := 0; i < n; i++ { + addr, pubKey := addressL[i], pubKeyL[i] + validator := teststaking.NewValidator(b, addr, pubKey) + ni := int64(i + 1) + validator.Tokens = sdk.NewInt(ni) + validator.DelegatorShares = sdk.NewDec(ni) + validators = append(validators, validator) + } + + b.ResetTimer() + for i := 0; i < b.N; i++ { + genesisState := types.DefaultGenesisState() + genesisState.Validators = validators + if err := staking.ValidateGenesis(genesisState); err != nil { + b.Fatal(err) + } + } +} + +func makeRandomAddressesAndPublicKeys(n int) (accL []sdk.ValAddress, pkL []*ed25519.PubKey) { + for i := 0; i < n; i++ { + pk := ed25519.GenPrivKey().PubKey().(*ed25519.PubKey) + pkL = append(pkL, pk) + accL = append(accL, sdk.ValAddress(pk.Address())) + } + return accL, pkL +}