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