Skip to content

Commit 35a2dbd

Browse files
authored
Improve context cancellation performance. (#248)
1 parent b36f73c commit 35a2dbd

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

conn.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ type Conn struct {
4141
busylst time.Time
4242
arena arena
4343
handle ptr_t
44+
nprogr uint8
4445
}
4546

4647
// Open calls [OpenFlags] with [OPEN_READWRITE], [OPEN_CREATE] and [OPEN_URI].
@@ -120,7 +121,7 @@ func (c *Conn) openDB(filename string, flags OpenFlag) (ptr_t, error) {
120121
return 0, err
121122
}
122123

123-
c.call("sqlite3_progress_handler_go", stk_t(handle), 100)
124+
c.call("sqlite3_progress_handler_go", stk_t(handle), 1000)
124125
if flags|OPEN_URI != 0 && strings.HasPrefix(filename, "file:") {
125126
var pragmas strings.Builder
126127
if _, after, ok := strings.Cut(filename, "?"); ok {
@@ -376,7 +377,7 @@ func (c *Conn) checkInterrupt(handle ptr_t) {
376377

377378
func progressCallback(ctx context.Context, mod api.Module, _ ptr_t) (interrupt int32) {
378379
if c, ok := ctx.Value(connKey{}).(*Conn); ok {
379-
if c.interrupt.Done() != nil {
380+
if c.nprogr++; c.nprogr%16 == 0 {
380381
runtime.Gosched()
381382
}
382383
if c.interrupt.Err() != nil {

driver/driver_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,3 +467,29 @@ func Test_ColumnType_ScanType(t *testing.T) {
467467
t.Fatal(err)
468468
}
469469
}
470+
471+
func Benchmark_loop(b *testing.B) {
472+
db, err := Open(":memory:")
473+
if err != nil {
474+
b.Fatal(err)
475+
}
476+
defer db.Close()
477+
478+
var version string
479+
err = db.QueryRow(`SELECT sqlite_version();`).Scan(&version)
480+
if err != nil {
481+
b.Fatal(err)
482+
}
483+
484+
ctx, cancel := context.WithCancel(context.Background())
485+
b.Cleanup(cancel)
486+
487+
b.ResetTimer()
488+
for range b.N {
489+
_, err := db.ExecContext(ctx,
490+
`WITH RECURSIVE c(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM c WHERE x < 1000000) SELECT x FROM c;`)
491+
if err != nil {
492+
b.Fatal(err)
493+
}
494+
}
495+
}

0 commit comments

Comments
 (0)