Skip to content

Commit

Permalink
btcutil: add benchmarks for Hash + WitnessHash
Browse files Browse the repository at this point in the history
  • Loading branch information
Roasbeef committed Dec 29, 2023
1 parent 56de9ca commit e102a81
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions btcutil/bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package btcutil_test

import (
"testing"

"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
)

var (
bencHash *chainhash.Hash
)

// BenchmarkTxHash benchmarks the performance of calculating the hash of a
// transaction.
func BenchmarkTxHash(b *testing.B) {
// Make a new block from the test block, we'll then call the Bytes
// function to cache the serialized block. Afterwards we all
// Transactions to populate the serialization cache.
testBlock := btcutil.NewBlock(&Block100000)
_, _ = testBlock.Bytes()

// The second transaction in the block has no witness data. The first
// does however.
testTx := testBlock.Transactions()[1]
testTx2 := testBlock.Transactions()[0]

// Run a benchmark for the portion that needs to strip the non-witness
// data from the transaction.
b.Run("tx_hash_has_witness", func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()

var txHash *chainhash.Hash
for i := 0; i < b.N; i++ {
txHash = testTx2.Hash()
}

bencHash = txHash
})

// Next, run it for the portion that can just hash the bytes directly.
b.Run("tx_hash_no_witness", func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()

var txHash *chainhash.Hash
for i := 0; i < b.N; i++ {
txHash = testTx.Hash()
}

bencHash = txHash
})

}

// BenchmarkTxWitnessHash benchmarks the performance of calculating the hash of
// a transaction.
func BenchmarkTxWitnessHash(b *testing.B) {
// Make a new block from the test block, we'll then call the Bytes
// function to cache the serialized block. Afterwards we all
// Transactions to populate the serialization cache.
testBlock := btcutil.NewBlock(&Block100000)
_, _ = testBlock.Bytes()

// The first transaction in the block has been modified to have witness
// data.
testTx := testBlock.Transactions()[0]

b.ResetTimer()
b.ReportAllocs()

var txHash *chainhash.Hash
for i := 0; i < b.N; i++ {
txHash = testTx.WitnessHash()
}

bencHash = txHash

}

0 comments on commit e102a81

Please sign in to comment.