-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark.go
More file actions
96 lines (75 loc) · 1.98 KB
/
Copy pathbenchmark.go
File metadata and controls
96 lines (75 loc) · 1.98 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
package main
import (
"context"
"fmt"
"log"
"sync"
"time"
"github.com/soumya-codes/postgres-conn-limits/internal/postgres"
)
const (
query = "SELECT pg_sleep(0.01);"
)
func main() {
config := postgres.Config{
Host: "localhost",
Port: 5432,
Username: "admin",
Password: "admin_password",
Database: "test_conn_pool_db",
}
// Benchmark the time taken to execute queries with and without connection pooling
BenchmarkNonPooledConnection(config, 10)
BenchmarkPooledConnection(config, 10, 10)
}
func BenchmarkNonPooledConnection(config postgres.Config, noOfQueries int) {
startTime := time.Now()
wg := sync.WaitGroup{}
for i := 0; i < noOfQueries; i++ {
wg.Add(1)
go func() {
defer wg.Done()
client, err := postgres.NewClient(config)
if err != nil {
log.Panic("Error connecting to Postgres:", err)
}
defer client.Close()
_, err = client.Conn.Exec(context.Background(), query)
if err != nil {
log.Panic("Error executing query:", err)
}
}()
wg.Wait()
}
fmt.Println("Time taken to execute queries without connection pooling:", time.Since(startTime))
}
func GetConnectionPool(config postgres.Config, maxConn int) (*postgres.ClientPool, error) {
pool, err := postgres.NewClientPool(config, maxConn)
if err != nil {
fmt.Println("Error creating connection pool:", err)
return nil, err
}
return pool, nil
}
func BenchmarkPooledConnection(config postgres.Config, noOfQueries int, maxConn int) {
pool, err := GetConnectionPool(config, maxConn)
if err != nil {
log.Panic("Error creating connection pool:", err)
}
startTime := time.Now()
wg := sync.WaitGroup{}
for i := 0; i < noOfQueries; i++ {
wg.Add(1)
go func() {
defer wg.Done()
client := pool.Acquire()
_, err = client.Conn.Exec(context.Background(), query)
if err != nil {
log.Panic("Error executing query:", err)
}
pool.Release(client)
}()
wg.Wait()
}
fmt.Println("Time taken to execute queries with connection pooling:", time.Since(startTime))
}