-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathperformance_check.go
More file actions
173 lines (139 loc) · 4.14 KB
/
Copy pathperformance_check.go
File metadata and controls
173 lines (139 loc) · 4.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
import (
"context"
"errors"
"flag"
"fmt"
"math/rand/v2"
"os"
"sync"
"sync/atomic"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
var (
numAccountsFlag = flag.Int("accounts", 10, "Number of accounts to create")
numWorkersFlag = flag.Int("workers", 20, "Number of concurrent workers")
durationFlag = flag.String("duration", "10s", "Duration to run the test (e.g., 30s, 1m, 5m)")
)
func parseArgs() (accounts, workers int, duration time.Duration) {
flag.Parse()
accounts = *numAccountsFlag
workers = *numWorkersFlag
if accounts < 2 {
fmt.Fprintf(os.Stderr, "Need at least 2 accounts to perform transfers.\n")
os.Exit(1)
}
duration, err := time.ParseDuration(*durationFlag)
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing runtime duration: %v\n", err)
os.Exit(1)
}
return
}
func main() {
numAccounts, numWorkers, runDuration := parseArgs()
ctx := context.Background()
dbconn := Must1(pgxpool.New(ctx, "postgres://pgledger:pgledger@localhost:5432/pgledger"))
defer dbconn.Close()
fmt.Printf("Creating %d accounts\n", numAccounts)
accountIDS := []string{}
for range numAccounts {
accountIDS = append(accountIDS, createAccount(ctx, dbconn))
}
fmt.Println("Running VACUUM FULL to clean up database")
Must1(dbconn.Exec(ctx, "VACUUM FULL"))
startingSizeBytes, startingSizePretty := dbSize(ctx, dbconn)
fmt.Printf("Starting %d workers to run transfers for %s\n", numWorkers, runDuration)
var wg sync.WaitGroup
var completedTransfers atomic.Int64
runCtx, cancel := context.WithTimeout(ctx, runDuration)
defer cancel()
wg.Add(numWorkers)
startTime := time.Now()
for range numWorkers {
go func() {
defer wg.Done()
for {
select {
case <-runCtx.Done():
return
default:
perm := rand.Perm(len(accountIDS))
from := accountIDS[perm[0]]
to := accountIDS[perm[1]]
createTransfer(runCtx, dbconn, from, to)
completed := completedTransfers.Add(1)
if completed%10000 == 0 {
fmt.Printf("- Completed %d transfers so far (elapsed: %d seconds)\n", completed, int(time.Since(startTime).Seconds()))
}
}
}
}()
}
fmt.Printf("Waiting for workers to finish (up to %s)...\n", runDuration)
wg.Wait()
elapsed := time.Since(startTime)
fmt.Println("Running VACUUM FULL to clean up database")
Must1(dbconn.Exec(ctx, "VACUUM FULL"))
endingSizeBytes, endingSizePretty := dbSize(ctx, dbconn)
totalCompleted := completedTransfers.Load()
// Avoid division by zero if no transfers were completed
bytesPerTransfer := int64(0)
if totalCompleted > 0 {
bytesPerTransfer = (endingSizeBytes - startingSizeBytes) / totalCompleted
}
fmt.Printf(`
Completed transfers: %d
Elapsed time in seconds: %f
Database size before: %s
Database size after: %s
Database size growth in bytes: %d
Transfers/second: %f
Bytes/transfer: %d
`,
completedTransfers.Load(),
elapsed.Seconds(),
startingSizePretty,
endingSizePretty,
endingSizeBytes-startingSizeBytes,
float64(totalCompleted)/elapsed.Seconds(),
bytesPerTransfer)
}
func Must1[T any](obj T, err error) T {
if err != nil {
panic(err)
}
return obj
}
func createAccount(ctx context.Context, conn *pgxpool.Pool) string {
rows := Must1(conn.Query(ctx, "select id from pgledger_create_account('acct', 'USD')"))
return Must1(pgx.CollectExactlyOneRow(rows, pgx.RowTo[string]))
}
func createTransfer(ctx context.Context, conn *pgxpool.Pool, fromAccountID, toAccountID string) {
rows, err := conn.Query(ctx, "select id from pgledger_create_transfer($1, $2, $3)", fromAccountID, toAccountID, rand.Uint32())
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return
}
panic(err)
}
_, err = pgx.CollectExactlyOneRow(rows, pgx.RowTo[string])
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return
}
panic(err)
}
}
func dbSize(ctx context.Context, conn *pgxpool.Pool) (int64, string) {
query := "select pg_database_size('pgledger') as size_bytes, pg_size_pretty(pg_database_size('pgledger')) as size_pretty"
var sizeBytes int64
var sizePretty string
err := conn.QueryRow(ctx, query).Scan(&sizeBytes, &sizePretty)
if err != nil {
panic(err)
}
return sizeBytes, sizePretty
}