-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
95 lines (77 loc) · 1.87 KB
/
main.go
File metadata and controls
95 lines (77 loc) · 1.87 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
package main
import (
"context"
"database/sql"
"fmt"
"log/slog"
"os"
"runtime"
"sync"
"sync/atomic"
"time"
_ "time/tzdata"
"github.com/google/uuid"
_ "github.com/jackc/pgx/v5/stdlib"
_ "embed"
)
//go:embed schema.sql
var queryCreate string
func main() {
// runtime.GOMAXPROCS(runtime.NumCPU())
loc, err := time.LoadLocation("UTC")
if err != nil {
panic(err)
}
time.Local = loc
dsn := os.ExpandEnv("user=$PSQL_USERNAME password=$PSQL_PASSWORD host=localhost port=5432 dbname=$PSQL_DB sslmode=disable")
db, err := sql.Open("pgx", dsn)
if err != nil {
slog.Error("db open failed", "error", err)
return
}
defer db.Close()
_, err = db.ExecContext(context.Background(), queryCreate)
if err != nil {
slog.Error("db create failed", "error", err)
return
}
slog.Info(`db create ok`)
query := `INSERT INTO impressions (impression_id, ad_id, image_url, click_url) VALUES ($1, $2, $3, $4)`
maxDuration := 1 * time.Second
startTime := time.Now()
var count uint64
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
timer := time.NewTimer(maxDuration)
go func() {
<-timer.C
cancel()
}()
workerCount := runtime.NumCPU()
var wg sync.WaitGroup
for range workerCount {
wg.Go(func() {
for i := 0; ; i++ {
select {
case <-ctx.Done():
return
default:
}
impressionID := uuid.New().String()
adID := "ad456"
imageURL := "https://example.com/image.jpg"
clickURL := "https://advertiser.com/click"
_, err := db.ExecContext(ctx, query, impressionID, adID, imageURL, clickURL)
if err != nil {
slog.Error("db insert failed", `i`, i, "error", err)
cancel()
return
}
atomic.AddUint64(&count, 1)
}
})
}
wg.Wait()
elapsed := time.Since(startTime)
fmt.Printf("Inserted %d rows in %.2f seconds (%.2f inserts/second)\n", count, elapsed.Seconds(), float64(count)/elapsed.Seconds())
}