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