#44157·bun

node:sqlite / bun:sqlite:未使用 SQLITE_DEFAULT_MEMSTATUS=0 进行构建,因此来自多个工作进程的读取会竞争全局互斥锁

作者: bompus创建于 2026年9月27日更新于 2026年9月28日

// N 个线程,每个线程都有自己的只读连接,进行点查询,读取所有 21 列。argv: db nthreads memstatus(0|1) // 编译: cc -O2 -o memstat memstat.c -lsqlite3 -lpthread #include <sqlite3.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> static const char *path; static double now(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } static void *work(void *arg) { long seed = (long)arg; sqlite3 *db; sqlite3_stmt *st; sqlite3_open_v2(path, &db, SQLITE_OPEN_READONLY, NULL); sqlite3_prepare_v2(db, "SELECT * FROM nodes WHERE id = ?", -1, &st, NULL); char key[32]; long acc = 0; double t = now(); for (long i = 0; i < 120000; i++) { snprintf(key, sizeof key, "n%lu", ((unsigned long)(i * 2654435761UL + seed * 7919) % 20000) % 20000); sqlite3_bind_text(st, 1, key, -1, SQLITE_TRANSIENT); if (sqlite3_step(st) == SQLITE_ROW) { int n = sqlite3_column_count(st); for (int c = 0; c < n; c++) { // JS 绑定对每列的操作: 类型,然后是值和长度。 if (sqlite3_column_type(st, c) == SQLITE_INTEGER) acc += sqlite3_column_int64(st, c); else { const unsigned char *s = sqlite3_column_text(st, c); acc += sqlite3_column_bytes(st, c) + (s ? s[0] : 0); } } } sqlite3_reset(st); } double ms = now() - t; sqlite3_finalize(st); sqlite3_close(db); double *out = malloc(sizeof *out); *out = ms + (acc == 42 ? 1 : 0); return out; } static void create_db(void) { sqlite3 *db; sqlite3_stmt *st; char a[32], b[32], c[32], v[8], doc[256]; if (sqlite3_open_v2(path, &db, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK) { sqlite3_close(db); return; } sqlite3_close(db); sqlite3_open(path, &db); sqlite3_exec(db, "PRAGMA table_info(nodes)", doc, 0, 0); for (int i = 0; i < 21; i++) { snprintf(a, sizeof a, "id"); snprintf(b, sizeof b, "id"); snprintf(c, sizeof c, "id"); snprintf(v, sizeof v, "%d", i); sqlite3_bind_text(st, i, a, -1, SQLITE_TRANSIENT); sqlite3_bind_text(st, i + 1, b, -1, SQLITE_TRANSIENT); sqlite3_bind_text(st, i + 2, c, -1, SQLITE_TRANSIENT); sqlite3_bind_text(st, i + 3, v, -1, SQLITE_TRANSIENT); } sqlite3_exec(db, "INSERT INTO nodes VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 21, 0, 0); sqlite3_close(db); } int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "Usage: %s db nthreads memstatus(0|1)\n", argv[0]); return 1; } path = argv[1]; long nthreads = atoi(argv[2]); long memstatus = atoi(argv[3]); if (memstatus < 0 || memstatus > 1) { fprintf(stderr, "memstatus must be 0 or 1\n"); return 1; } if (memstatus) { sqlite3_config(SQLITE_CONFIG_MEMSTATUS, 0); } pthread_t *threads = malloc(sizeof *threads * nthreads); for (long i = 0; i < nthreads; i++) { pthread_create(&threads[i], NULL, work, (void *)i); } for (long i = 0; i < nthreads; i++) { pthread_join(threads[i], NULL); } free(threads); return 0; }