bench_test.go raw
1 package ffldb
2
3 import (
4 block2 "github.com/p9c/p9/pkg/block"
5 "os"
6 "path/filepath"
7 "testing"
8
9 "github.com/p9c/p9/pkg/chaincfg"
10 "github.com/p9c/p9/pkg/database"
11 )
12
13 // BenchmarkBlockHeader benchmarks how long it takes to load the mainnet genesis block header.
14 func BenchmarkBlockHeader(b *testing.B) {
15 // Start by creating a new database and populating it with the mainnet genesis block.
16 dbPath := filepath.Join(os.TempDir(), "ffldb-benchblkhdr")
17 _ = os.RemoveAll(dbPath)
18 db, e := database.Create("ffldb", dbPath, blockDataNet)
19 if e != nil {
20 b.Fatal(e)
21 }
22 defer func() {
23 if e = os.RemoveAll(dbPath); E.Chk(e) {
24 }
25 }()
26 defer func() {
27 if e = db.Close(); E.Chk(e) {
28 }
29 }()
30 e = db.Update(func(tx database.Tx) (e error) {
31 block := block2.NewBlock(chaincfg.MainNetParams.GenesisBlock)
32 return tx.StoreBlock(block)
33 },
34 )
35 if e != nil {
36 b.Fatal(e)
37 }
38 b.ReportAllocs()
39 b.ResetTimer()
40 e = db.View(func(tx database.Tx) (e error) {
41 blockHash := chaincfg.MainNetParams.GenesisHash
42 for i := 0; i < b.N; i++ {
43 _, e := tx.FetchBlockHeader(blockHash)
44 if e != nil {
45 return e
46 }
47 }
48 return nil
49 },
50 )
51 if e != nil {
52 b.Fatal(e)
53 }
54 // Don't benchmark teardown.
55 b.StopTimer()
56 }
57
58 // BenchmarkBlockHeader benchmarks how long it takes to load the mainnet genesis block.
59 func BenchmarkBlock(b *testing.B) {
60 // Start by creating a new database and populating it with the mainnet genesis block.
61 dbPath := filepath.Join(os.TempDir(), "ffldb-benchblk")
62 _ = os.RemoveAll(dbPath)
63 db, e := database.Create("ffldb", dbPath, blockDataNet)
64 if e != nil {
65 b.Fatal(e)
66 }
67 defer func() {
68 if e = os.RemoveAll(dbPath); E.Chk(e) {
69 }
70 }()
71 defer func() {
72 if e = db.Close(); E.Chk(e) {
73 }
74 }()
75 e = db.Update(func(tx database.Tx) (e error) {
76 block := block2.NewBlock(chaincfg.MainNetParams.GenesisBlock)
77 return tx.StoreBlock(block)
78 },
79 )
80 if e != nil {
81 b.Fatal(e)
82 }
83 b.ReportAllocs()
84 b.ResetTimer()
85 e = db.View(func(tx database.Tx) (e error) {
86 blockHash := chaincfg.MainNetParams.GenesisHash
87 for i := 0; i < b.N; i++ {
88 _, e := tx.FetchBlock(blockHash)
89 if e != nil {
90 return e
91 }
92 }
93 return nil
94 },
95 )
96 if e != nil {
97 b.Fatal(e)
98 }
99 // Don't benchmark teardown.
100 b.StopTimer()
101 }
102