Debian Codegraph @

callback_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 "sync"
13 "sync/atomic"
14 "testing"
15 "unsafe"
16 )
17
18 func BenchmarkHandleLookupParallel(b *testing.B) {
19 d := SQLiteDriver{}
20 conn, err := d.Open(":memory:")
21 if err != nil {
22 b.Fatal(err)
23 }
24 defer conn.Close()
25 c := conn.(*SQLiteConn)
26
27 handle := newHandle(c, func() {})
28
29 benchmarkHandleLookupParallel(b, func() any {
30 return lookupHandle(handle)
31 })
32 }
33
34 func BenchmarkHandleLookupBeforeAfter(b *testing.B) {
35 value := handleVal{val: func() {}}
36 handle := unsafe.Pointer(&value)
37
38 before := mutexHandleTable{vals: map[unsafe.Pointer]handleVal{handle: value}}
39 after := atomicHandleTable{}
40 after.vals.Store(map[unsafe.Pointer]handleVal{handle: value})
41
42 b.Run("before_mutex", func(b *testing.B) {
43 benchmarkHandleLookupParallel(b, func() any {
44 return before.lookup(handle).val
45 })
46 })
47 b.Run("after_atomic", func(b *testing.B) {
48 benchmarkHandleLookupParallel(b, func() any {
49 return after.lookup(handle).val
50 })
51 })
52 }
53
54 func benchmarkHandleLookupParallel(b *testing.B, lookup func() any) {
55 b.Helper()
56 b.ReportAllocs()
57 b.ResetTimer()
58 b.RunParallel(func(pb *testing.PB) {
59 for pb.Next() {
60 if lookup() == nil {
61 b.Fatal("lookup returned nil")
62 }
63 }
64 })
65 }
66
67 type mutexHandleTable struct {
68 mu sync.Mutex
69 vals map[unsafe.Pointer]handleVal
70 }
71
72 func (t *mutexHandleTable) lookup(handle unsafe.Pointer) handleVal {
73 t.mu.Lock()
74 defer t.mu.Unlock()
75 return t.vals[handle]
76 }
77
78 type atomicHandleTable struct {
79 vals atomic.Value
80 }
81
82 func (t *atomicHandleTable) lookup(handle unsafe.Pointer) handleVal {
83 m, _ := t.vals.Load().(map[unsafe.Pointer]handleVal)
84 return m[handle]
85 }