There are several places when processing blocks and headers that require the ability to traverse the chain to ancestors of a given block such as tallying votes and versions to determine threshold states, finding forks, and calculating PoW difficulty, ticket price, and sequence locks. Currently most traversal of this type is linear and therefore does not scale well as the chain height grows. In addition, the ability to quickly locate ancestors, potentially deep in history, will be needed when decoupling the connection code from the download logic as well as several planned future optimizations. Consequently, this significantly optimizes ancestor traversal by introducing a deterministic skip list and adds tests to ensure proper functionality. The following is a before and after comparison of ancestor traversal for a large number of nodes: benchmark old ns/op new ns/op delta ------------------------------------------------------ BenchmarkAncestor 67901581 158 -100.00% benchmark old allocs new allocs delta ------------------------------------------------------ BenchmarkAncestor 0 0 +0.00% benchmark old bytes new bytes delta ------------------------------------------------------ BenchmarkAncestor 0 0 +0.00%
33 lines
1.1 KiB
Go
33 lines
1.1 KiB
Go
// Copyright (c) 2019 The Decred developers
|
|
// Use of this source code is governed by an ISC
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package blockchain
|
|
|
|
import (
|
|
"testing"
|
|
)
|
|
|
|
// BenchmarkAncestor benchmarks ancestor traversal for various numbers of nodes.
|
|
func BenchmarkAncestor(b *testing.B) {
|
|
// Construct a synthetic block chain with consisting of the following
|
|
// structure.
|
|
// 0 -> 1 -> 2 -> ... -> 499997 -> 499998 -> 499999 -> 500000
|
|
// \-> 499999a
|
|
// \-> 499998a
|
|
branch0Nodes := chainedFakeSkipListNodes(nil, 500001)
|
|
branch1Nodes := chainedFakeSkipListNodes(branch0Nodes[499998], 1)
|
|
branch2Nodes := chainedFakeSkipListNodes(branch0Nodes[499997], 1)
|
|
|
|
b.ReportAllocs()
|
|
b.ResetTimer()
|
|
for i := 0; i < b.N; i++ {
|
|
branchTip(branch0Nodes).Ancestor(0)
|
|
branchTip(branch0Nodes).Ancestor(131072) // Power of two.
|
|
branchTip(branch0Nodes).Ancestor(131071) // One less than power of two.
|
|
branchTip(branch0Nodes).Ancestor(131070) // Two less than power of two.
|
|
branchTip(branch1Nodes).Ancestor(0)
|
|
branchTip(branch2Nodes).Ancestor(0)
|
|
}
|
|
}
|