Debian Codegraph @

sqlite3_stmt_cache_bench_test.go

raw
1 // Copyright (C) 2019 Yasuhiro Matsumoto <[email protected]>.
2 //
3 // Use of this source code is governed by an MIT-style
4 // license that can be found in the LICENSE file.
5
6 //go:build cgo
7 // +build cgo
8
9 package sqlite3
10
11 import (
12 "context"
13 "database/sql/driver"
14 "fmt"
15 "testing"
16 )
17
18 // BenchmarkStmtCache measures the stmt cache hit / miss / eviction paths by
19 // cycling through a fixed set of queries under various cache sizes. It is
20 // intended for comparing cache behavior changes, not for absolute numbers.
21 func BenchmarkStmtCache(b *testing.B) {
22 cases := []struct {
23 name string
24 cacheSize int
25 keyCount int
26 }{
27 {"off", 0, 1}, // baseline: no cache
28 {"size4_keys1_hit", 4, 1}, // trivial hit path
29 {"size4_keys4_hit", 4, 4}, // all queries fit, always hit
30 {"size4_keys8_evict", 4, 8}, // working set > cache: miss + eviction
31 {"size16_keys8_hit", 16, 8}, // all queries fit in larger cache
32 {"size16_keys32_evict", 16, 32}, // working set >> cache
33 }
34 for _, tc := range cases {
35 b.Run(tc.name, func(b *testing.B) {
36 dsn := ":memory:"
37 if tc.cacheSize > 0 {
38 dsn = fmt.Sprintf(":memory:?_stmt_cache_size=%d", tc.cacheSize)
39 }
40 d := SQLiteDriver{}
41 conn, err := d.Open(dsn)
42 if err != nil {
43 b.Fatal(err)
44 }
45 defer conn.Close()
46 c := conn.(*SQLiteConn)
47
48 queries := make([]string, tc.keyCount)
49 for i := range queries {
50 // Distinct literal forces a distinct prepared statement.
51 queries[i] = fmt.Sprintf("SELECT %d", i+1)
52 }
53
54 ctx := context.Background()
55 // Warm up: exercise each query at least once so the cache (if any)
56 // reaches steady state before timing begins.
57 for _, q := range queries {
58 rows, err := c.query(ctx, q, nil)
59 if err != nil {
60 b.Fatal(err)
61 }
62 drainRows(b, rows)
63 }
64
65 b.ReportAllocs()
66 b.ResetTimer()
67 for i := 0; i < b.N; i++ {
68 q := queries[i%len(queries)]
69 rows, err := c.query(ctx, q, nil)
70 if err != nil {
71 b.Fatal(err)
72 }
73 drainRows(b, rows)
74 }
75 })
76 }
77 }
78
79 func drainRows(b *testing.B, rows driver.Rows) {
80 b.Helper()
81 dest := make([]driver.Value, len(rows.Columns()))
82 for {
83 if err := rows.Next(dest); err != nil {
84 break
85 }
86 }
87 rows.Close()
88 }