Each run of the full benchmark leaves a JSON file in
results/dbbench/,
with the machine, the versions and, for each engine and question, three timings. The tables
below are a Polars query over those files (run is when it started, in UTC), as in the other benchmark chapters: two rounds
of unnest and unpivot give one row per engine and question, and list.min keeps the
best of the timed runs.
let index = @["run", "machine", "cpu", "nanuq", "rows"]
proc timings(path: string): DataFrame =
readJson(path)
.select(
col.timestamp.str.slice(0, 16).alias("run"),
col.label.alias("machine"),
col.system.struct.field("cpu"),
col.versions.struct.field("nanuqWrapper").alias("nanuq"),
col.params.struct.field("rows"),
col.timings)
.unnest("timings")
.unpivot(index = index, variableName = "engine", valueName = "questions")
.unnest("questions")
.unpivot(index = index & "engine", variableName = "question", valueName = "seconds")
let times = concat(sorted(toSeq(walkFiles("../results/dbbench/*.json"))).mapIt(timings(it)),
how = ConcatMethod.Vertical)
.withColumns(col.seconds.list.min)
nbShow times.head(3)
shape: (3, 8)
run
machine
cpu
nanuq
rows
engine
question
seconds
str
str
str
str
i64
str
str
f64
"2026-11-02T14:10"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2โฆ
"0.6.0"
10000000
"nanuq in-memory"
"g1"
0.550306
"2026-11-02T14:10"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2โฆ
"0.6.0"
10000000
"python in-memory"
"g1"
0.579615
"2026-11-02T14:10"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2โฆ
"0.6.0"
10000000
"python streaming"
"g1"
0.453072
import glob
import polars as pl
index = ["run", "machine", "cpu", "nanuq", "rows"]
def timings(path):
return (
pl.read_json(path)
.select(
pl.col("timestamp").str.slice(0, 16).alias("run"),
pl.col("label").alias("machine"),
pl.col("system").struct.field("cpu"),
pl.col("versions").struct.field("nanuqWrapper").alias("nanuq"),
pl.col("params").struct.field("rows"),
"timings",
)
.unnest("timings")
.unpivot(index=index, variable_name="engine", value_name="questions")
.unnest("questions")
.unpivot(index=[*index, "engine"], variable_name="question", value_name="seconds")
)
times = pl.concat(
[timings(path) for path in sorted(glob.glob("../results/dbbench/*.json"))]
).with_columns(pl.col("seconds").list.min())
times.head(3)
shape: (3, 8)
run
machine
cpu
nanuq
rows
engine
question
seconds
str
str
str
str
i64
str
str
f64
"2026-11-02T14:10"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2โฆ
"0.6.0"
10000000
"nanuq in-memory"
"g1"
0.550306
"2026-11-02T14:10"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2โฆ
"0.6.0"
10000000
"python in-memory"
"g1"
0.579615
"2026-11-02T14:10"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2โฆ
"0.6.0"
10000000
"python streaming"
"g1"
0.453072
The total time of each run, one column per engine:
db-benchmark times dataframe libraries and
databases on two tasks: ten group-by questions on a table of 10 million to 1 billion rows,
and five joins. It is the benchmark where Polars first made its name, in 2021, and it is
still run on every new version of the tools it covers.
The group-by table has six id columns of different kinds and sizes and three values:
column
what
groups
id1, id2
strings id001โฆ
K (100)
id3
strings id0000000001โฆ
N/K
id4, id5
integers
K
id6
integers
N/K
v1, v2
integers in 1โ5 and 1โ15
v3
a float in [0, 100)
The join tables are a left table x of N rows and three right tables of N/10โถ (small), N/10ยณ
(medium) and N rows (big), whose keys overlap 90% with x's.
The questions are in bench/dbbench.nim
and bench/dbbench.py.
When the book is built, each one runs on both sides on 10,000 rows, and the build checks that
the two tables are the same (sorted by their keys, so that the rows shown match).
Group-by questions
g1: sum v1 by id1
proc g1*(x: LazyFrame): LazyFrame =
## sum v1 by id1
x.groupBy("id1").agg(col.v1.sum.alias("v1_sum"))
shape: (100, 2)
id1
v1_sum
cat
i32
"id001"
286
"id002"
270
"id003"
324
"id004"
323
"id005"
316
…
…
"id096"
330
"id097"
219
"id098"
303
"id099"
306
"id100"
300
def g1(x):
# sum v1 by id1
return x.group_by("id1").agg(pl.sum("v1").alias("v1_sum"))
shape: (100, 2)
id1
v1_sum
cat
i32
"id001"
286
"id002"
270
"id003"
324
"id004"
323
"id005"
316
…
…
"id096"
330
"id097"
219
"id098"
303
"id099"
306
"id100"
300
g2: sum v1 by id1:id2
proc g2*(x: LazyFrame): LazyFrame =
## sum v1 by id1:id2
x.groupBy("id1", "id2").agg(col.v1.sum.alias("v1_sum"))
shape: (6_316, 3)
id1
id2
v1_sum
cat
cat
i32
"id001"
"id002"
2
"id001"
"id005"
9
"id001"
"id006"
2
"id001"
"id007"
7
"id001"
"id008"
4
…
…
…
"id100"
"id095"
9
"id100"
"id096"
1
"id100"
"id097"
4
"id100"
"id098"
13
"id100"
"id100"
1
def g2(x):
# sum v1 by id1:id2
return x.group_by(["id1", "id2"]).agg(pl.sum("v1").alias("v1_sum"))
shape: (6_316, 3)
id1
id2
v1_sum
cat
cat
i32
"id001"
"id002"
2
"id001"
"id005"
9
"id001"
"id006"
2
"id001"
"id007"
7
"id001"
"id008"
4
…
…
…
"id100"
"id095"
9
"id100"
"id096"
1
"id100"
"id097"
4
"id100"
"id098"
13
"id100"
"id100"
1
g3: sum v1 mean v3 by id3
proc g3*(x: LazyFrame): LazyFrame =
## sum v1 mean v3 by id3
x.groupBy("id3").agg(col.v1.sum.alias("v1_sum"), col.v3.mean.alias("v3_mean"))
shape: (100, 3)
id3
v1_sum
v3_mean
cat
i32
f64
"id0000000001"
335
54.082505
"id0000000002"
256
49.287781
"id0000000003"
278
53.871425
"id0000000004"
309
51.090055
"id0000000005"
273
54.813354
…
…
…
"id0000000096"
332
52.427157
"id0000000097"
307
54.555622
"id0000000098"
264
46.759033
"id0000000099"
302
48.80176
"id0000000100"
272
56.616213
def g3(x):
# sum v1 mean v3 by id3
return x.group_by("id3").agg([pl.sum("v1").alias("v1_sum"), pl.mean("v3").alias("v3_mean")])
shape: (100, 3)
id3
v1_sum
v3_mean
cat
i32
f64
"id0000000001"
335
54.082505
"id0000000002"
256
49.287781
"id0000000003"
278
53.871425
"id0000000004"
309
51.090055
"id0000000005"
273
54.813354
…
…
…
"id0000000096"
332
52.427157
"id0000000097"
307
54.555622
"id0000000098"
264
46.759033
"id0000000099"
302
48.80176
"id0000000100"
272
56.616213
g4: mean v1:v3 by id4
proc g4*(x: LazyFrame): LazyFrame =
## mean v1:v3 by id4
x.groupBy("id4").agg(col.v1.mean.alias("v1_mean"), col.v2.mean.alias("v2_mean"),
col.v3.mean.alias("v3_mean"))
shape: (100, 4)
id4
v1_mean
v2_mean
v3_mean
i32
f64
f64
f64
1
2.98374
7.715447
45.562441
2
2.961165
7.747573
51.106608
3
3.146067
7.898876
52.24703
4
2.826923
7.846154
45.140535
5
2.912621
8.203883
50.60851
…
…
…
…
96
2.77
8.22
45.680176
97
3.032609
8.26087
51.217574
98
2.941748
7.815534
46.405132
99
3.04
8.23
50.539987
100
3.010638
7.882979
49.862361
def g4(x):
# mean v1:v3 by id4
return x.group_by("id4").agg([pl.mean("v1").alias("v1_mean"), pl.mean("v2").alias("v2_mean"),
pl.mean("v3").alias("v3_mean")])
shape: (100, 4)
id4
v1_mean
v2_mean
v3_mean
i32
f64
f64
f64
1
2.98374
7.715447
45.562441
2
2.961165
7.747573
51.106608
3
3.146067
7.898876
52.24703
4
2.826923
7.846154
45.140535
5
2.912621
8.203883
50.60851
…
…
…
…
96
2.77
8.22
45.680176
97
3.032609
8.26087
51.217574
98
2.941748
7.815534
46.405132
99
3.04
8.23
50.539987
100
3.010638
7.882979
49.862361
g5: sum v1:v3 by id6
proc g5*(x: LazyFrame): LazyFrame =
## sum v1:v3 by id6
x.groupBy("id6").agg(col.v1.sum.alias("v1_sum"), col.v2.sum.alias("v2_sum"),
col.v3.sum.alias("v3_sum"))
shape: (100, 4)
id6
v1_sum
v2_sum
v3_sum
i32
i32
i32
f64
1
289
672
4819.901325
2
305
927
5624.686782
3
269
830
4773.060168
4
337
854
5693.493764
5
332
921
5251.951351
…
…
…
…
96
281
819
4801.252673
97
293
731
4722.388982
98
333
937
5507.241385
99
288
833
4894.383037
100
345
856
5321.822027
def g5(x):
# sum v1:v3 by id6
return x.group_by("id6").agg([pl.sum("v1").alias("v1_sum"), pl.sum("v2").alias("v2_sum"),
pl.sum("v3").alias("v3_sum")])
shape: (100, 4)
id6
v1_sum
v2_sum
v3_sum
i32
i32
i32
f64
1
289
672
4819.901325
2
305
927
5624.686782
3
269
830
4773.060168
4
337
854
5693.493764
5
332
921
5251.951351
…
…
…
…
96
281
819
4801.252673
97
293
731
4722.388982
98
333
937
5507.241385
99
288
833
4894.383037
100
345
856
5321.822027
g6: median v3 sd v3 by id4 id5
proc g6*(x: LazyFrame): LazyFrame =
## median v3 sd v3 by id4 id5
x.groupBy("id4", "id5").agg(col.v3.median.alias("v3_median"), col.v3.std.alias("v3_std"))
shape: (6_245, 4)
id4
id5
v3_median
v3_std
i32
i32
f64
f64
1
2
19.818959
14.835572
1
3
56.744619
49.498784
1
5
79.855389
14.947513
1
6
79.940378
null
1
7
18.429828
null
…
…
…
…
100
94
22.90576
24.587197
100
95
99.495246
null
100
96
62.527365
20.259614
100
99
33.358999
null
100
100
15.911042
null
def g6(x):
# median v3 sd v3 by id4 id5
return x.group_by(["id4", "id5"]).agg([pl.median("v3").alias("v3_median"),
pl.std("v3").alias("v3_std")])
shape: (6_245, 4)
id4
id5
v3_median
v3_std
i32
i32
f64
f64
1
2
19.818959
14.835572
1
3
56.744619
49.498784
1
5
79.855389
14.947513
1
6
79.940378
null
1
7
18.429828
null
…
…
…
…
100
94
22.90576
24.587197
100
95
99.495246
null
100
96
62.527365
20.259614
100
99
33.358999
null
100
100
15.911042
null
g7: max v1 - min v2 by id3
proc g7*(x: LazyFrame): LazyFrame =
## max v1 - min v2 by id3
x.groupBy("id3").agg((col.v1.max - col.v2.min).alias("range_v1_v2"))
shape: (100, 2)
id3
range_v1_v2
cat
i32
"id0000000001"
4
"id0000000002"
4
"id0000000003"
4
"id0000000004"
4
"id0000000005"
4
…
…
"id0000000096"
4
"id0000000097"
4
"id0000000098"
4
"id0000000099"
4
"id0000000100"
4
def g7(x):
# max v1 - min v2 by id3
return x.group_by("id3").agg([(pl.max("v1") - pl.min("v2")).alias("range_v1_v2")])
shape: (100, 2)
id3
range_v1_v2
cat
i32
"id0000000001"
4
"id0000000002"
4
"id0000000003"
4
"id0000000004"
4
"id0000000005"
4
…
…
"id0000000096"
4
"id0000000097"
4
"id0000000098"
4
"id0000000099"
4
"id0000000100"
4
g8: largest two v3 by id6
proc g8*(x: LazyFrame): LazyFrame =
## largest two v3 by id6
x.dropNulls("v3").groupBy("id6").agg(col.v3.topK(2).alias("largest2_v3"))
.explode("largest2_v3")
shape: (200, 2)
id6
largest2_v3
i32
f64
1
99.28818
1
99.868033
2
98.009352
2
99.763516
3
99.476037
…
…
98
99.408389
99
98.77951
99
99.625273
100
99.32078
100
99.891088
def g8(x):
# largest two v3 by id6
return x.drop_nulls("v3").group_by("id6").agg(col("v3").top_k(2).alias("largest2_v3")) \
.explode("largest2_v3")
proc g10*(x: LazyFrame): LazyFrame =
## sum v3 count by id1:id6
x.groupBy("id1", "id2", "id3", "id4", "id5", "id6")
.agg(col.v3.sum.alias("v3"), len().alias("count"))
shape: (10_000, 8)
id1
id2
id3
id4
id5
id6
v3
count
cat
cat
cat
i32
i32
i32
f64
u32
"id001"
"id002"
"id0000000059"
98
53
23
11.453623
1
"id001"
"id005"
"id0000000011"
20
67
30
96.094689
1
"id001"
"id005"
"id0000000065"
27
80
23
29.151617
1
"id001"
"id006"
"id0000000051"
26
95
96
77.626782
1
"id001"
"id007"
"id0000000019"
15
44
89
31.032376
1
…
…
…
…
…
…
…
…
"id100"
"id098"
"id0000000015"
35
58
94
94.888389
1
"id100"
"id098"
"id0000000024"
10
67
98
68.647809
1
"id100"
"id098"
"id0000000032"
66
54
93
66.215942
1
"id100"
"id098"
"id0000000076"
84
91
47
61.042446
1
"id100"
"id100"
"id0000000080"
38
79
50
92.326713
1
def g10(x):
# sum v3 count by id1:id6
return x.group_by(["id1", "id2", "id3", "id4", "id5", "id6"]) \
.agg([pl.sum("v3").alias("v3"), pl.len().alias("count")])
shape: (10_000, 8)
id1
id2
id3
id4
id5
id6
v3
count
cat
cat
cat
i32
i32
i32
f64
u32
"id001"
"id002"
"id0000000059"
98
53
23
11.453623
1
"id001"
"id005"
"id0000000011"
20
67
30
96.094689
1
"id001"
"id005"
"id0000000065"
27
80
23
29.151617
1
"id001"
"id006"
"id0000000051"
26
95
96
77.626782
1
"id001"
"id007"
"id0000000019"
15
44
89
31.032376
1
…
…
…
…
…
…
…
…
"id100"
"id098"
"id0000000015"
35
58
94
94.888389
1
"id100"
"id098"
"id0000000024"
10
67
98
68.647809
1
"id100"
"id098"
"id0000000032"
66
54
93
66.215942
1
"id100"
"id098"
"id0000000076"
84
91
47
61.042446
1
"id100"
"id100"
"id0000000080"
38
79
50
92.326713
1
Join questions
j1: small inner on int
proc j1*(t: JoinTables): LazyFrame =
## small inner on int
t.x.join(t.small, on = ["id1"])
shape: (8_972, 9)
id1
id2
id3
id4
id5
id6
v1
id4_right
v2
i32
i32
i32
cat
cat
cat
f32
cat
f32
2
2
10
"id2"
"id2"
"id10"
37.221138
"id2"
83.823555
2
2
1727
"id2"
"id2"
"id1727"
5.158724
"id2"
83.823555
2
2
2092
"id2"
"id2"
"id2092"
43.574284
"id2"
83.823555
2
2
3306
"id2"
"id2"
"id3306"
51.576077
"id2"
83.823555
2
2
4569
"id2"
"id2"
"id4569"
12.448287
"id2"
83.823555
…
…
…
…
…
…
…
…
…
11
108
6037
"id11"
"id108"
"id6037"
39.281113
"id11"
95.907318
11
108
7655
"id11"
"id108"
"id7655"
88.79631
"id11"
95.907318
11
108
8030
"id11"
"id108"
"id8030"
45.440418
"id11"
95.907318
11
108
8276
"id11"
"id108"
"id8276"
60.417381
"id11"
95.907318
11
108
8524
"id11"
"id108"
"id8524"
22.404985
"id11"
95.907318
def j1(t):
# small inner on int
return t["x"].join(t["small"], on="id1")
shape: (8_972, 9)
id1
id2
id3
id4
id5
id6
v1
id4_right
v2
i32
i32
i32
cat
cat
cat
f32
cat
f32
2
2
10
"id2"
"id2"
"id10"
37.221138
"id2"
83.823555
2
2
1727
"id2"
"id2"
"id1727"
5.158724
"id2"
83.823555
2
2
2092
"id2"
"id2"
"id2092"
43.574284
"id2"
83.823555
2
2
3306
"id2"
"id2"
"id3306"
51.576077
"id2"
83.823555
2
2
4569
"id2"
"id2"
"id4569"
12.448287
"id2"
83.823555
…
…
…
…
…
…
…
…
…
11
108
6037
"id11"
"id108"
"id6037"
39.281113
"id11"
95.907318
11
108
7655
"id11"
"id108"
"id7655"
88.79631
"id11"
95.907318
11
108
8030
"id11"
"id108"
"id8030"
45.440418
"id11"
95.907318
11
108
8276
"id11"
"id108"
"id8276"
60.417381
"id11"
95.907318
11
108
8524
"id11"
"id108"
"id8524"
22.404985
"id11"
95.907318
j2: medium inner on int
proc j2*(t: JoinTables): LazyFrame =
## medium inner on int
t.x.join(t.medium, on = ["id2"])
shape: (9_100, 11)
id1
id2
id3
id4
id5
id6
v1
id1_right
id4_right
id5_right
v2
i32
i32
i32
cat
cat
cat
f32
i32
cat
cat
f32
2
2
10
"id2"
"id2"
"id10"
37.221138
1
"id1"
"id2"
42.161072
2
2
1727
"id2"
"id2"
"id1727"
5.158724
1
"id1"
"id2"
42.161072
2
2
2092
"id2"
"id2"
"id2092"
43.574284
1
"id1"
"id2"
42.161072
2
2
3306
"id2"
"id2"
"id3306"
51.576077
1
"id1"
"id2"
42.161072
2
2
4569
"id2"
"id2"
"id4569"
12.448287
1
"id1"
"id2"
42.161072
…
…
…
…
…
…
…
…
…
…
…
11
108
6037
"id11"
"id108"
"id6037"
39.281113
9
"id9"
"id108"
98.272331
11
108
7655
"id11"
"id108"
"id7655"
88.79631
9
"id9"
"id108"
98.272331
11
108
8030
"id11"
"id108"
"id8030"
45.440418
9
"id9"
"id108"
98.272331
11
108
8276
"id11"
"id108"
"id8276"
60.417381
9
"id9"
"id108"
98.272331
11
108
8524
"id11"
"id108"
"id8524"
22.404985
9
"id9"
"id108"
98.272331
def j2(t):
# medium inner on int
return t["x"].join(t["medium"], on="id2")
shape: (9_100, 11)
id1
id2
id3
id4
id5
id6
v1
id1_right
id4_right
id5_right
v2
i32
i32
i32
cat
cat
cat
f32
i32
cat
cat
f32
2
2
10
"id2"
"id2"
"id10"
37.221138
1
"id1"
"id2"
42.161072
2
2
1727
"id2"
"id2"
"id1727"
5.158724
1
"id1"
"id2"
42.161072
2
2
2092
"id2"
"id2"
"id2092"
43.574284
1
"id1"
"id2"
42.161072
2
2
3306
"id2"
"id2"
"id3306"
51.576077
1
"id1"
"id2"
42.161072
2
2
4569
"id2"
"id2"
"id4569"
12.448287
1
"id1"
"id2"
42.161072
…
…
…
…
…
…
…
…
…
…
…
11
108
6037
"id11"
"id108"
"id6037"
39.281113
9
"id9"
"id108"
98.272331
11
108
7655
"id11"
"id108"
"id7655"
88.79631
9
"id9"
"id108"
98.272331
11
108
8030
"id11"
"id108"
"id8030"
45.440418
9
"id9"
"id108"
98.272331
11
108
8276
"id11"
"id108"
"id8276"
60.417381
9
"id9"
"id108"
98.272331
11
108
8524
"id11"
"id108"
"id8524"
22.404985
9
"id9"
"id108"
98.272331
j3: medium outer on int
proc j3*(t: JoinTables): LazyFrame =
## medium outer on int (a left join, as in db-benchmark)
t.x.join(t.medium, on = ["id2"], how = Left)
shape: (10_000, 11)
id1
id2
id3
id4
id5
id6
v1
id1_right
id4_right
id5_right
v2
i32
i32
i32
cat
cat
cat
f32
i32
cat
cat
f32
2
2
10
"id2"
"id2"
"id10"
37.221138
1
"id1"
"id2"
42.161072
2
2
1727
"id2"
"id2"
"id1727"
5.158724
1
"id1"
"id2"
42.161072
2
2
2092
"id2"
"id2"
"id2092"
43.574284
1
"id1"
"id2"
42.161072
2
2
3306
"id2"
"id2"
"id3306"
51.576077
1
"id1"
"id2"
42.161072
2
2
4569
"id2"
"id2"
"id4569"
12.448287
1
"id1"
"id2"
42.161072
…
…
…
…
…
…
…
…
…
…
…
11
108
6037
"id11"
"id108"
"id6037"
39.281113
9
"id9"
"id108"
98.272331
11
108
7655
"id11"
"id108"
"id7655"
88.79631
9
"id9"
"id108"
98.272331
11
108
8030
"id11"
"id108"
"id8030"
45.440418
9
"id9"
"id108"
98.272331
11
108
8276
"id11"
"id108"
"id8276"
60.417381
9
"id9"
"id108"
98.272331
11
108
8524
"id11"
"id108"
"id8524"
22.404985
9
"id9"
"id108"
98.272331
def j3(t):
# medium outer on int (a left join, as in db-benchmark)
return t["x"].join(t["medium"], how="left", on="id2")
shape: (10_000, 11)
id1
id2
id3
id4
id5
id6
v1
id1_right
id4_right
id5_right
v2
i32
i32
i32
cat
cat
cat
f32
i32
cat
cat
f32
2
2
10
"id2"
"id2"
"id10"
37.221138
1
"id1"
"id2"
42.161072
2
2
1727
"id2"
"id2"
"id1727"
5.158724
1
"id1"
"id2"
42.161072
2
2
2092
"id2"
"id2"
"id2092"
43.574284
1
"id1"
"id2"
42.161072
2
2
3306
"id2"
"id2"
"id3306"
51.576077
1
"id1"
"id2"
42.161072
2
2
4569
"id2"
"id2"
"id4569"
12.448287
1
"id1"
"id2"
42.161072
…
…
…
…
…
…
…
…
…
…
…
11
108
6037
"id11"
"id108"
"id6037"
39.281113
9
"id9"
"id108"
98.272331
11
108
7655
"id11"
"id108"
"id7655"
88.79631
9
"id9"
"id108"
98.272331
11
108
8030
"id11"
"id108"
"id8030"
45.440418
9
"id9"
"id108"
98.272331
11
108
8276
"id11"
"id108"
"id8276"
60.417381
9
"id9"
"id108"
98.272331
11
108
8524
"id11"
"id108"
"id8524"
22.404985
9
"id9"
"id108"
98.272331
j4: medium inner on factor
proc j4*(t: JoinTables): LazyFrame =
## medium inner on factor
t.x.join(t.medium, on = ["id5"])
shape: (9_100, 11)
id1
id2
id3
id4
id5
id6
v1
id1_right
id2_right
id4_right
v2
i32
i32
i32
cat
cat
cat
f32
i32
i32
cat
f32
2
2
10
"id2"
"id2"
"id10"
37.221138
1
2
"id1"
42.161072
2
2
1727
"id2"
"id2"
"id1727"
5.158724
1
2
"id1"
42.161072
2
2
2092
"id2"
"id2"
"id2092"
43.574284
1
2
"id1"
42.161072
2
2
3306
"id2"
"id2"
"id3306"
51.576077
1
2
"id1"
42.161072
2
2
4569
"id2"
"id2"
"id4569"
12.448287
1
2
"id1"
42.161072
…
…
…
…
…
…
…
…
…
…
…
11
108
6037
"id11"
"id108"
"id6037"
39.281113
9
108
"id9"
98.272331
11
108
7655
"id11"
"id108"
"id7655"
88.79631
9
108
"id9"
98.272331
11
108
8030
"id11"
"id108"
"id8030"
45.440418
9
108
"id9"
98.272331
11
108
8276
"id11"
"id108"
"id8276"
60.417381
9
108
"id9"
98.272331
11
108
8524
"id11"
"id108"
"id8524"
22.404985
9
108
"id9"
98.272331
def j4(t):
# medium inner on factor
return t["x"].join(t["medium"], on="id5")
shape: (9_100, 11)
id1
id2
id3
id4
id5
id6
v1
id1_right
id2_right
id4_right
v2
i32
i32
i32
cat
cat
cat
f32
i32
i32
cat
f32
2
2
10
"id2"
"id2"
"id10"
37.221138
1
2
"id1"
42.161072
2
2
1727
"id2"
"id2"
"id1727"
5.158724
1
2
"id1"
42.161072
2
2
2092
"id2"
"id2"
"id2092"
43.574284
1
2
"id1"
42.161072
2
2
3306
"id2"
"id2"
"id3306"
51.576077
1
2
"id1"
42.161072
2
2
4569
"id2"
"id2"
"id4569"
12.448287
1
2
"id1"
42.161072
…
…
…
…
…
…
…
…
…
…
…
11
108
6037
"id11"
"id108"
"id6037"
39.281113
9
108
"id9"
98.272331
11
108
7655
"id11"
"id108"
"id7655"
88.79631
9
108
"id9"
98.272331
11
108
8030
"id11"
"id108"
"id8030"
45.440418
9
108
"id9"
98.272331
11
108
8276
"id11"
"id108"
"id8276"
60.417381
9
108
"id9"
98.272331
11
108
8524
"id11"
"id108"
"id8524"
22.404985
9
108
"id9"
98.272331
j5: big inner on int
proc j5*(t: JoinTables): LazyFrame =
## big inner on int
t.x.join(t.big, on = ["id3"])
shape: (9_000, 13)
id1
id2
id3
id4
id5
id6
v1
id1_right
id2_right
id4_right
id5_right
id6_right
v2
i32
i32
i32
cat
cat
cat
f32
i32
i32
cat
cat
cat
f32
2
2
10
"id2"
"id2"
"id10"
37.221138
6
34
"id6"
"id34"
"id10"
6.600459
2
2
1727
"id2"
"id2"
"id1727"
5.158724
10
23
"id10"
"id23"
"id1727"
46.574547
2
2
2092
"id2"
"id2"
"id2092"
43.574284
10
97
"id10"
"id97"
"id2092"
67.648369
2
2
3306
"id2"
"id2"
"id3306"
51.576077
8
84
"id8"
"id84"
"id3306"
15.445398
2
2
4569
"id2"
"id2"
"id4569"
12.448287
3
75
"id3"
"id75"
"id4569"
59.754215
…
…
…
…
…
…
…
…
…
…
…
…
…
11
108
6037
"id11"
"id108"
"id6037"
39.281113
9
22
"id9"
"id22"
"id6037"
8.298156
11
108
7655
"id11"
"id108"
"id7655"
88.79631
6
23
"id6"
"id23"
"id7655"
69.442337
11
108
8030
"id11"
"id108"
"id8030"
45.440418
6
107
"id6"
"id107"
"id8030"
83.096092
11
108
8276
"id11"
"id108"
"id8276"
60.417381
7
1
"id7"
"id1"
"id8276"
59.613743
11
108
8524
"id11"
"id108"
"id8524"
22.404985
7
87
"id7"
"id87"
"id8524"
99.756798
def j5(t):
# big inner on int
return t["x"].join(t["big"], on="id3")
shape: (9_000, 13)
id1
id2
id3
id4
id5
id6
v1
id1_right
id2_right
id4_right
id5_right
id6_right
v2
i32
i32
i32
cat
cat
cat
f32
i32
i32
cat
cat
cat
f32
2
2
10
"id2"
"id2"
"id10"
37.221138
6
34
"id6"
"id34"
"id10"
6.600459
2
2
1727
"id2"
"id2"
"id1727"
5.158724
10
23
"id10"
"id23"
"id1727"
46.574547
2
2
2092
"id2"
"id2"
"id2092"
43.574284
10
97
"id10"
"id97"
"id2092"
67.648369
2
2
3306
"id2"
"id2"
"id3306"
51.576077
8
84
"id8"
"id84"
"id3306"
15.445398
2
2
4569
"id2"
"id2"
"id4569"
12.448287
3
75
"id3"
"id75"
"id4569"
59.754215
…
…
…
…
…
…
…
…
…
…
…
…
…
11
108
6037
"id11"
"id108"
"id6037"
39.281113
9
22
"id9"
"id22"
"id6037"
8.298156
11
108
7655
"id11"
"id108"
"id7655"
88.79631
6
23
"id6"
"id23"
"id7655"
69.442337
11
108
8030
"id11"
"id108"
"id8030"
45.440418
6
107
"id6"
"id107"
"id8030"
83.096092
11
108
8276
"id11"
"id108"
"id8276"
60.417381
7
1
"id7"
"id1"
"id8276"
59.613743
11
108
8524
"id11"
"id108"
"id8524"
22.404985
7
87
"id7"
"id87"
"id8524"
99.756798
Running it on your machine
From the root of a clone of the book, with Nim, nimble, uv and git (the script installs the
book's dependencies first; the data goes to bench-data/, which git ignores; 10 million rows
are about 0.5 GB of group-by CSV and 0.7 GB of join CSV):
scripts/bench dbbench # 10 million rows, 3 timed runs per question
scripts/bench dbbench -d:benchRows=100000000 # 100 million rows
scripts/bench dbbench -d:benchLabel=my-laptop # a name for your machine
It writes the timings and the machine's specs to a timestamped file in results/dbbench/
and commits it; a pull request with that file adds a run to the tables at the top.
Source files
Every source file this page mentions, folded: tap one to read it. A file's name in the text leads here.
bench/dbbench.nim186 lines
## The db-benchmark (H2O.ai, now DuckDB Labs) group-by and join questions in Nanuq,## and data generators that follow its R scripts.#### Ported from db-benchmark's `polars/groupby-polars.py` and `polars/join-polars.py`## (MPL-2.0); the generators follow `_data/groupby-datagen.R` and `_data/join-datagen.R`.import std/[os, random, strutils, sequtils]
import nanuq
# --- Data ---------------------------------------------------------------------------proc fmtId(prefix: string, n, width: int): string = prefix & align($n, width, '0')
proc generateGroupBy*(path: string, n, k: int, seed = 108) =
## `n` rows of the group-by table, as `groupby-datagen.R` makes them with `k` groups## (no missing values, random order): id1, id2 (k strings each), id3 (n/k strings),## id4, id5 (k ints), id6 (n/k ints), v1 in 1..5, v2 in 1..15, v3 in [0, 100).var r = initRand(seed)
var f = open(path, fmWrite)
defer: f.close()
f.writeLine "id1,id2,id3,id4,id5,id6,v1,v2,v3"let nk = max(n div k, 1)
for _ in0 ..< n:
f.writeLine fmtId("id", r.rand(1 .. k), 3), ',', fmtId("id", r.rand(1 .. k), 3), ',',
fmtId("id", r.rand(1 .. nk), 10), ',', r.rand(1 .. k), ',', r.rand(1 .. k), ',',
r.rand(1 .. nk), ',', r.rand(1 .. 5), ',', r.rand(1 .. 15), ',',
formatFloat(r.rand(100.0), ffDecimal, 6)
typeJoinSizes* = tuple[small, medium, big: int]
proc joinSizes*(n: int): JoinSizes =
## Rows of the three right-hand tables: n/1e6, n/1e3 and n in db-benchmark (whose## smallest x has 1e7 rows); at least 10 and 100 here, so small samples join too.
(max(n div1_000_000, 10), max(n div1_000, 100), n)
proc generateJoin*(dir: string, n: int, seed = 108) =
## The join tables as `join-datagen.R` makes them: `x.csv` (`n` rows) and `small.csv`,## `medium.csv`, `big.csv`. Each key column draws from its own pool of keys: 90% are## shared by both sides, 10% only on the left, 10% only on the right; id4..id6 are the## same keys as strings.var r = initRand(seed)
let sizes = joinSizes(n)
proc split(m: int): tuple[x, l, rr: seq[int]] =
var key = toSeq(1 .. (m * 11) div10)
r.shuffle(key)
let a = (m * 9) div10
(key[0 ..< a], key[a ..< m], key[m .. ^1])
proc sampleAll(keys: seq[int], size: int): seq[int] =
# every key at least once, then random ones, shuffledresult = keys
whileresult.len < size: result.add keys[r.rand(keys.high)]
result.setLen size
r.shuffle(result)
let k1 = split(sizes.small)
let k2 = split(sizes.medium)
let k3 = split(sizes.big)
createDir dir
block:
let id1 = sampleAll(k1.x & k1.l, n)
let id2 = sampleAll(k2.x & k2.l, n)
let id3 = sampleAll(k3.x & k3.l, n)
var f = open(dir / "x.csv", fmWrite)
f.writeLine "id1,id2,id3,id4,id5,id6,v1"for i in0 ..< n:
f.writeLine id1[i], ',', id2[i], ',', id3[i], ",id", id1[i], ",id", id2[i], ",id", id3[i],
',', formatFloat(r.rand(100.0), ffDecimal, 6)
f.close()
block:
let id1 = sampleAll(k1.x & k1.rr, sizes.small)
var f = open(dir / "small.csv", fmWrite)
f.writeLine "id1,id4,v2"for i in0 ..< sizes.small:
f.writeLine id1[i], ",id", id1[i], ',', formatFloat(r.rand(100.0), ffDecimal, 6)
f.close()
block:
let id1 = sampleAll(k1.x & k1.rr, sizes.medium)
let id2 = sampleAll(k2.x & k2.rr, sizes.medium)
var f = open(dir / "medium.csv", fmWrite)
f.writeLine "id1,id2,id4,id5,v2"for i in0 ..< sizes.medium:
f.writeLine id1[i], ',', id2[i], ",id", id1[i], ",id", id2[i], ',',
formatFloat(r.rand(100.0), ffDecimal, 6)
f.close()
block:
let id1 = sampleAll(k1.x & k1.rr, sizes.big)
let id2 = sampleAll(k2.x & k2.rr, sizes.big)
let id3 = sampleAll(k3.x & k3.rr, sizes.big)
var f = open(dir / "big.csv", fmWrite)
f.writeLine "id1,id2,id3,id4,id5,id6,v2"for i in0 ..< sizes.big:
f.writeLine id1[i], ',', id2[i], ',', id3[i], ",id", id1[i], ",id", id2[i], ",id", id3[i],
',', formatFloat(r.rand(100.0), ffDecimal, 6)
f.close()
# --- Reading, as the Polars scripts do ----------------------------------------------proc scanGroupBy*(path: string): LazyFrame =
## The group-by table, with its string ids as Categorical.
scanCsv(path, schemaOverrides = {"id4": Int32, "id5": Int32, "id6": Int32,
"v1": Int32, "v2": Int32, "v3": Float64})
.withColumns(col(["id1", "id2", "id3"]).cast(Categorical))
typeJoinTables* = object
x*, small*, medium*, big*: LazyFrameproc scanJoin*(dir: string): JoinTables =
## The four join tables, with their string ids as Categorical.JoinTables(
x: scanCsv(dir / "x.csv", schemaOverrides = {"id1": Int32, "id2": Int32, "id3": Int32,
"v1": Float32})
.withColumns(col(["id4", "id5", "id6"]).cast(Categorical)),
small: scanCsv(dir / "small.csv", schemaOverrides = {"id1": Int32, "v2": Float32})
.withColumns(col.id4.cast(Categorical)),
medium: scanCsv(dir / "medium.csv", schemaOverrides = {"id1": Int32, "id2": Int32,
"v2": Float32})
.withColumns(col(["id4", "id5"]).cast(Categorical)),
big: scanCsv(dir / "big.csv", schemaOverrides = {"id1": Int32, "id2": Int32, "id3": Int32,
"v2": Float32})
.withColumns(col(["id4", "id5", "id6"]).cast(Categorical)))
# --- Group-by questions ---------------------------------------------------------------proc g1*(x: LazyFrame): LazyFrame =
## sum v1 by id1
x.groupBy("id1").agg(col.v1.sum.alias("v1_sum"))
proc g2*(x: LazyFrame): LazyFrame =
## sum v1 by id1:id2
x.groupBy("id1", "id2").agg(col.v1.sum.alias("v1_sum"))
proc g3*(x: LazyFrame): LazyFrame =
## sum v1 mean v3 by id3
x.groupBy("id3").agg(col.v1.sum.alias("v1_sum"), col.v3.mean.alias("v3_mean"))
proc g4*(x: LazyFrame): LazyFrame =
## mean v1:v3 by id4
x.groupBy("id4").agg(col.v1.mean.alias("v1_mean"), col.v2.mean.alias("v2_mean"),
col.v3.mean.alias("v3_mean"))
proc g5*(x: LazyFrame): LazyFrame =
## sum v1:v3 by id6
x.groupBy("id6").agg(col.v1.sum.alias("v1_sum"), col.v2.sum.alias("v2_sum"),
col.v3.sum.alias("v3_sum"))
proc g6*(x: LazyFrame): LazyFrame =
## median v3 sd v3 by id4 id5
x.groupBy("id4", "id5").agg(col.v3.median.alias("v3_median"), col.v3.std.alias("v3_std"))
proc g7*(x: LazyFrame): LazyFrame =
## max v1 - min v2 by id3
x.groupBy("id3").agg((col.v1.max - col.v2.min).alias("range_v1_v2"))
proc g8*(x: LazyFrame): LazyFrame =
## largest two v3 by id6
x.dropNulls("v3").groupBy("id6").agg(col.v3.topK(2).alias("largest2_v3"))
.explode("largest2_v3")
proc g9*(x: LazyFrame): LazyFrame =
## regression v1 v2 by id2 id4
x.groupBy("id2", "id4").agg(corr("v1", "v2").pow(2).alias("r2"))
proc g10*(x: LazyFrame): LazyFrame =
## sum v3 count by id1:id6
x.groupBy("id1", "id2", "id3", "id4", "id5", "id6")
.agg(col.v3.sum.alias("v3"), len().alias("count"))
# --- Join questions -------------------------------------------------------------------proc j1*(t: JoinTables): LazyFrame =
## small inner on int
t.x.join(t.small, on = ["id1"])
proc j2*(t: JoinTables): LazyFrame =
## medium inner on int
t.x.join(t.medium, on = ["id2"])
proc j3*(t: JoinTables): LazyFrame =
## medium outer on int (a left join, as in db-benchmark)
t.x.join(t.medium, on = ["id2"], how = Left)
proc j4*(t: JoinTables): LazyFrame =
## medium inner on factor
t.x.join(t.medium, on = ["id5"])
proc j5*(t: JoinTables): LazyFrame =
## big inner on int
t.x.join(t.big, on = ["id3"])
bench/dbbench.nim
bench/dbbench.py114 lines
"""The db-benchmark (H2O.ai, now DuckDB Labs) group-by and join questions in Python Polars.
The queries are those of db-benchmark's polars/groupby-polars.py and polars/join-polars.py
(MPL-2.0), as functions of the lazy tables.
"""import os
import polars as pl
from polars import col
def scan_groupby(path):
# The group-by table, with its string ids as Categorical.return pl.scan_csv(
path,
schema_overrides={"id4": pl.Int32, "id5": pl.Int32, "id6": pl.Int32,
"v1": pl.Int32, "v2": pl.Int32, "v3": pl.Float64},
).with_columns(pl.col(["id1", "id2", "id3"]).cast(pl.Categorical))
def scan_join(dir):
# The four join tables, with their string ids as Categorical.def scan(name, overrides, cats):
return pl.scan_csv(os.path.join(dir, name + ".csv"), schema_overrides=overrides) \
.with_columns(pl.col(cats).cast(pl.Categorical))
return {
"x": scan("x", {"id1": pl.Int32, "id2": pl.Int32, "id3": pl.Int32, "v1": pl.Float32},
["id4", "id5", "id6"]),
"small": scan("small", {"id1": pl.Int32, "v2": pl.Float32}, ["id4"]),
"medium": scan("medium", {"id1": pl.Int32, "id2": pl.Int32, "v2": pl.Float32},
["id4", "id5"]),
"big": scan("big", {"id1": pl.Int32, "id2": pl.Int32, "id3": pl.Int32,
"v2": pl.Float32}, ["id4", "id5", "id6"]),
}
def g1(x):
# sum v1 by id1return x.group_by("id1").agg(pl.sum("v1").alias("v1_sum"))
def g2(x):
# sum v1 by id1:id2return x.group_by(["id1", "id2"]).agg(pl.sum("v1").alias("v1_sum"))
def g3(x):
# sum v1 mean v3 by id3return x.group_by("id3").agg([pl.sum("v1").alias("v1_sum"), pl.mean("v3").alias("v3_mean")])
def g4(x):
# mean v1:v3 by id4return x.group_by("id4").agg([pl.mean("v1").alias("v1_mean"), pl.mean("v2").alias("v2_mean"),
pl.mean("v3").alias("v3_mean")])
def g5(x):
# sum v1:v3 by id6return x.group_by("id6").agg([pl.sum("v1").alias("v1_sum"), pl.sum("v2").alias("v2_sum"),
pl.sum("v3").alias("v3_sum")])
def g6(x):
# median v3 sd v3 by id4 id5return x.group_by(["id4", "id5"]).agg([pl.median("v3").alias("v3_median"),
pl.std("v3").alias("v3_std")])
def g7(x):
# max v1 - min v2 by id3return x.group_by("id3").agg([(pl.max("v1") - pl.min("v2")).alias("range_v1_v2")])
def g8(x):
# largest two v3 by id6return x.drop_nulls("v3").group_by("id6").agg(col("v3").top_k(2).alias("largest2_v3")) \
.explode("largest2_v3")
def g9(x):
# regression v1 v2 by id2 id4return x.group_by(["id2", "id4"]).agg((pl.corr("v1", "v2", method="pearson") ** 2).alias("r2"))
def g10(x):
# sum v3 count by id1:id6return x.group_by(["id1", "id2", "id3", "id4", "id5", "id6"]) \
.agg([pl.sum("v3").alias("v3"), pl.len().alias("count")])
def j1(t):
# small inner on intreturn t["x"].join(t["small"], on="id1")
def j2(t):
# medium inner on intreturn t["x"].join(t["medium"], on="id2")
def j3(t):
# medium outer on int (a left join, as in db-benchmark)return t["x"].join(t["medium"], how="left", on="id2")
def j4(t):
# medium inner on factorreturn t["x"].join(t["medium"], on="id5")
def j5(t):
# big inner on intreturn t["x"].join(t["big"], on="id3")
bench/dbbench.py
book/benchkit.nim: timing, results and tables of the benchmark chapters138 lines
## Helpers for the benchmark chapters.#### A benchmark chapter builds in two ways:## - normally (`nimble genbook`, CI): it runs its queries on a small sample, to check## that Nim and Python agree, and shows every result file in `results/<bench>/`,## as a Nanuq query over those files;## - with `-d:bench` (`scripts/bench <bench>`, on your machine): it first runs the## benchmark at full size, times the Nim and the Python queries, writes a timestamped## JSON file with the timings and the machine's specs to `results/<bench>/`, and## commits it.import std/[json, options, os, osproc, strutils, times, monotimes, sequtils, math, xmltree]
import nanuq
import nanuqbook
const
benchRuns* {.intdefine.} = 3## timed runs of each query (the best one counts)
benchLabel* {.strdefine.} = ""## a name for the machine, such as "pietro-mac"proc resultsDir*(bench: string): string =
## results/<bench>, seen from the chapter's working directory (docs/).".." / "results" / bench
proc cmd(c: string): string =
try:
let (o, code) = execCmdEx(c)
if code == 0: o.strip else: ""exceptOSError: ""proc systemInfo*(): JsonNode =
## The machine the benchmark runs on.var cpu, memBytes: stringwhendefined(macosx):
cpu = cmd("sysctl -n machdep.cpu.brand_string")
memBytes = cmd("sysctl -n hw.memsize")
else:
for line in cmd("cat /proc/cpuinfo").splitLines:
if line.startsWith("model name"):
cpu = line.split(':', 1)[1].strip
breakfor line in cmd("cat /proc/meminfo").splitLines:
if line.startsWith("MemTotal:"):
memBytes = $(parseInt(line.splitWhitespace[1]) * 1024)
let memGb = if memBytes.len > 0: round(parseFloat(memBytes) / 1e9, 1) else: 0.0var osName = cmd("uname -sr")
whendefined(macosx):
osName = "macOS " & cmd("sw_vers -productVersion")
%*{"os": osName, "arch": hostCPU, "cpu": cpu, "cores": countProcessors(),
"memoryGB": memGb}
proc timeIt*(runs: int, body: proc ()): seq[float] =
## Seconds taken by each of `runs` runs of `body`.for _ in1 .. runs:
let start = getMonoTime()
body()
result.add (getMonoTime() - start).inNanoseconds.float / 1e9proc timePython*(runs: int, call: string): seq[float] =
## Seconds taken by each of `runs` runs of the Python expression `call`, in the## chapter's Python session.let (printed, _) = runPython("""
import time as _time
_times = []
for _ in range(""" & $runs & """):
_start = _time.perf_counter()
""" & call & """
_times.append(_time.perf_counter() - _start)
print(" ".join(repr(t) for t in _times))
""")
printed.splitWhitespace.mapIt(parseFloat(it))
proc pythonVersions*(): JsonNode =
let (printed, _) = runPython("""
import platform as _platform, polars as _pl
print(_platform.python_version(), _pl.__version__)
""")
let v = printed.splitWhitespace
%*{"python": v[0], "pythonPolars": v[1]}
proc saveResult*(bench: string, params, timings: JsonNode): string =
## Writes results/<bench>/<timestamp>[-<label>].json and commits it. Returns its path.let now = now().utc
var versions = %*{"nim": NimVersion, "nanuqWrapper": polarsWrapperVersion()}
for k, v in pythonVersions(): versions[k] = v
let data = %*{"benchmark": bench, "timestamp": now.format("yyyy-MM-dd'T'HH:mm:ss'Z'"),
"label": benchLabel, "params": params, "system": systemInfo(),
"versions": versions, "timings": timings}
createDir resultsDir(bench)
var name = now.format("yyyyMMdd'T'HHmmss'Z'")
if benchLabel.len > 0: name.add "-" & benchLabel
result = resultsDir(bench) / name & ".json"
writeFile result, data.pretty & "\n"echo"[bench] wrote ", resultlet (o, code) = execCmdEx("git add " & quoteShell(result) & " && git commit -q -m " &
quoteShell("Benchmark result: " & bench & " " & name) & " -- " & quoteShell(result))
if code == 0: echo"[bench] committed ", resultelse: echo"[bench] could not commit ", result, ":\n", o
proc markdownTable*(df: DataFrame, boldLast = false): string =
## `df` as a Markdown table, as readers want it: capitalised headers, seconds with two## decimals, rows with separators, "-" for nulls. `boldLast` is for a row of totals.let names = df.columns
result = "| " & names.mapIt(it.capitalizeAscii).join(" | ") & " |\n| " &
names.mapIt(if df.dtype(it) == String: "---"else: "--:").join(" | ") & " |\n"for i in0 ..< df.height:
var cells: seq[string]
for name in names:
let dtype = df.dtype(name)
var cell = "-"if dtype == Float64:
let x = df[name, i, Option[float]]
if x.isSome: cell = formatFloat(x.get, ffDecimal, 2) & " s"elif dtype == Int64:
cell = insertSep($df[name, i, int], ',')
else:
cell = df[name, i, string]
cells.add (if boldLast and i == df.height - 1and cell != "-": "**" & cell & "**"else: cell)
result.add "| " & cells.join(" | ") & " |\n"proc queryTabs*(nimSrc, pySrc: string, nimFrame: DataFrame, pyCall: string): string =
## A query's Nim and Python source in tabs, each with the table it gives (the Python## one from running `pyCall`); fails the build if the two tables differ.let nimSide = "<pre><code class=\"nim-file nohighlight nim hljs\">" &
highlightNim(nimSrc.strip) & "</code></pre>" & nimFrame.toHtml
let (_, pyShown) = runPython(pyCall)
checkSameFrame(nimSide, pyShown, pyCall)
tabsHtml(nimSide, "<pre><code class=\"language-python py-file hljs\">" &
xmltree.escape(pySrc.strip) & "</code></pre>" & pyShown)
proc sourcePart*(source, start: string, stops: openArray[string]): string =
## The part of `source` from the line starting with `start` to the next `stops`.let i = source.find(start)
doAssert i >= 0, "not found: " & start
var j = source.len
for s in stops:
let k = source.find(s, i + start.len)
if k >= 0and k < j: j = k
source[i ..< j].strip
book/benchkit.nim
scripts/bench: a full run on your machine23 lines
#!/bin/sh
# Runs a benchmark chapter of the book at full size, on this machine:
#
# scripts/bench 1brc|pdsh|dbbench [nim options]
#
# e.g. `scripts/bench 1brc -d:benchRows=100000000 -d:benchLabel=my-laptop` or
# `scripts/bench pdsh -d:benchScale=10`.
# The chapter times the Nim and the Python queries, writes the timings and the
# machine's specs to results/<benchmark>/<timestamp>[-label].json, commits that
# file, and rebuilds its page. Needs Nim (with nimble), uv and git; run it from the
# repository root. It installs the book's Nim and Python dependencies first.
set -e
cd "$(dirname "$0")/.."
case "$1" in
1brc) chapter=book/benchmarks/one_billion_rows.nim ;;
pdsh) chapter=book/benchmarks/pds_h.nim ;;
dbbench) chapter=book/benchmarks/db_benchmark.nim ;;
*) echo "usage: scripts/bench 1brc|pdsh|dbbench [nim options]" >&2; exit 2 ;;
esac
shift
nimble install -y --depsOnly
uv sync --locked --quiet
exec uv run nim r -d:release -d:bench --hints:off "$@" "$chapter"
scripts/bench
import nanuq, nanuqbook, benchkit, dbbench
import ../foldcode
import std/[algorithm, os, json, strutils, sequtils]
bookInit()
const
benchRows {.intdefine.} = 10_000_000## rows of a full run (`-d:benchRows=...`)
benchGroups {.intdefine.} = 100## K, the number of groups of id1, id2, id4, id5
nbText: "# Group-by and join (db-benchmark)"
nanuq """
**About this chapter.** The questions are ported from the Polars scripts of
[db-benchmark](https://github.com/duckdblabs/db-benchmark) (started by H2O.ai, now kept by
DuckDB Labs), licensed under the
[Mozilla Public License 2.0](https://github.com/pietroppeter/nanuq-book/blob/main/licenses/db-benchmark-MPL-2.0.txt).
The data generators in [`bench/dbbench.nim`](#src-bench-dbbench-nim) follow its R scripts (`groupby-datagen.R` and
`join-datagen.R`), with Nim's random numbers, so the values differ from the R ones. The data
is made on the fly and never stored in the repository. The text is the book's own.
The code of the benchmark is folded under [Source files](#source-files), at the end.
"""typeGroupQ = tuple[name, title: string, keys: seq[string], run: proc (x: LazyFrame): LazyFrame]
JoinQ = tuple[name, title: string, run: proc (t: JoinTables): LazyFrame]
let groupQs: seq[GroupQ] = @[
("g1", "sum v1 by id1", @["id1"], g1),
("g2", "sum v1 by id1:id2", @["id1", "id2"], g2),
("g3", "sum v1 mean v3 by id3", @["id3"], g3),
("g4", "mean v1:v3 by id4", @["id4"], g4),
("g5", "sum v1:v3 by id6", @["id6"], g5),
("g6", "median v3 sd v3 by id4 id5", @["id4", "id5"], g6),
("g7", "max v1 - min v2 by id3", @["id3"], g7),
("g8", "largest two v3 by id6", @["id6", "largest2_v3"], g8),
("g9", "regression v1 v2 by id2 id4", @["id2", "id4"], g9),
("g10", "sum v3 count by id1:id6", @["id1", "id2", "id3", "id4", "id5", "id6"], g10)]
let joinQs: seq[JoinQ] = @[
("j1", "small inner on int", j1),
("j2", "medium inner on int", j2),
("j3", "medium outer on int", j3),
("j4", "medium inner on factor", j4),
("j5", "big inner on int", j5)]
proc groupByFile(rows: int): string =
result = ".." / "bench-data" / "dbbench" / "G1_" & $rows & "_" & $benchGroups & ".csv"ifnot fileExists(result):
createDir result.parentDir
generateGroupBy(result, rows, benchGroups)
proc joinDir(rows: int): string =
result = ".." / "bench-data" / "dbbench" / "J1_" & $rows
ifnot fileExists(result / "big.csv"):
generateJoin(result, rows)
proc loadPython(gfile, jdir: string) =
discard runPython("import sys\nsys.path.insert(0, '../bench')\nfrom dbbench import *\n" &
"_x = scan_groupby(" & escapeJson(gfile) & ")\n" &
"_t = scan_join(" & escapeJson(jdir) & ")")
# --- A full run: only with -d:bench -------------------------------------------------whendefined(bench):
let gfile = groupByFile(benchRows)
let jdir = joinDir(benchRows)
let x = scanGroupBy(gfile)
let t = scanJoin(jdir)
loadPython(gfile, jdir)
var nimMemory, nimStreaming, pyMemory, pyStreaming = newJObject()
for q in groupQs:
echo"[bench] ", q.name
nimMemory[q.name] = %timeIt(benchRuns, proc () = discard q.run(x).collect(Engine.InMemory))
nimStreaming[q.name] = %timeIt(benchRuns, proc () = discard q.run(x).collect(Engine.Streaming))
pyMemory[q.name] = %timePython(benchRuns, q.name & "(_x).collect(engine='in-memory')")
pyStreaming[q.name] = %timePython(benchRuns, q.name & "(_x).collect(engine='streaming')")
for q in joinQs:
echo"[bench] ", q.name
nimMemory[q.name] = %timeIt(benchRuns, proc () = discard q.run(t).collect(Engine.InMemory))
nimStreaming[q.name] = %timeIt(benchRuns, proc () = discard q.run(t).collect(Engine.Streaming))
pyMemory[q.name] = %timePython(benchRuns, q.name & "(_t).collect(engine='in-memory')")
pyStreaming[q.name] = %timePython(benchRuns, q.name & "(_t).collect(engine='streaming')")
discard saveResult("dbbench", %*{"rows": benchRows, "groups": benchGroups, "runs": benchRuns},
%*{"nanuq in-memory": nimMemory, "nanuq streaming": nimStreaming,
"python in-memory": pyMemory, "python streaming": pyStreaming})
# --- Results ----------------------------------------------------------------------
nbText: """
## Results
Each run of the full benchmark leaves a JSON file in
[`results/dbbench/`](https://github.com/pietroppeter/nanuq-book/tree/main/results/dbbench),
with the machine, the versions and, for each engine and question, three timings. The tables
below are a Polars query over those files (`run` is when it started, in UTC), as in the other benchmark chapters: two rounds
of `unnest` and `unpivot` give one row per engine and question, and `list.min` keeps the
best of the timed runs.
"""
tabs """
import glob
import polars as pl
index = ["run", "machine", "cpu", "nanuq", "rows"]
def timings(path):
return (
pl.read_json(path)
.select(
pl.col("timestamp").str.slice(0, 16).alias("run"),
pl.col("label").alias("machine"),
pl.col("system").struct.field("cpu"),
pl.col("versions").struct.field("nanuqWrapper").alias("nanuq"),
pl.col("params").struct.field("rows"),
"timings",
)
.unnest("timings")
.unpivot(index=index, variable_name="engine", value_name="questions")
.unnest("questions")
.unpivot(index=[*index, "engine"], variable_name="question", value_name="seconds")
)
times = pl.concat(
[timings(path) for path in sorted(glob.glob("../results/dbbench/*.json"))]
).with_columns(pl.col("seconds").list.min())
times.head(3)
""":
nbCode:
let index = @["run", "machine", "cpu", "nanuq", "rows"]
proc timings(path: string): DataFrame =
readJson(path)
.select(
col.timestamp.str.slice(0, 16).alias("run"),
col.label.alias("machine"),
col.system.struct.field("cpu"),
col.versions.struct.field("nanuqWrapper").alias("nanuq"),
col.params.struct.field("rows"),
col.timings)
.unnest("timings")
.unpivot(index = index, variableName = "engine", valueName = "questions")
.unnest("questions")
.unpivot(index = index & "engine", variableName = "question", valueName = "seconds")
let times = concat(sorted(toSeq(walkFiles("../results/dbbench/*.json"))).mapIt(timings(it)),
how = ConcatMethod.Vertical)
.withColumns(col.seconds.list.min)
nbShow times.head(3)
nbText: """
The total time of each run, one column per engine:
"""
tabs """
(
times.group_by([*index, "engine"], maintain_order=True)
.agg(pl.col("seconds").sum().round(2))
.pivot(on="engine", index=index, values="seconds", sort_columns=True)
)
""":
nbCode:
nbShow times
.groupBy(index & "engine", maintainOrder = true)
.agg(col.seconds.sum.round(2))
.pivot(on = "engine", index = index, values = "seconds", sortColumns = true)
nbText: """
And question by question, on the latest run:
"""
tabs """
pl.Config.set_tbl_rows(15) # the default shows 10 rows
(
times.filter(pl.col("run") == pl.col("run").max())
.with_columns(pl.col("seconds").round(3))
.pivot(on="engine", index="question", values="seconds", sort_columns=True)
)
""":
nbCode:
let byQuestion = times
.filter(col.run == col.run.max)
.withColumns(col.seconds.round(3))
.pivot(on = "engine", index = "question", values = "seconds", sortColumns = true)
nbRawHtml: byQuestion.toHtml(maxRows = 15) # the default shows 10 rowsdiscard runPython("pl.Config.set_tbl_rows(10)")
nanuq """
Timings are in seconds, reading the CSV files included.
"""
nbText: "## The benchmark"
nbText: """
[db-benchmark](https://duckdblabs.github.io/db-benchmark/) times dataframe libraries and
databases on two tasks: ten group-by questions on a table of 10 million to 1 billion rows,
and five joins. It is the benchmark where Polars first made its name, in 2021, and it is
still run on every new version of the tools it covers.
The group-by table has six id columns of different kinds and sizes and three values:
| column | what | groups |
| ------ | ---- | ------ |
| `id1`, `id2` | strings `id001`โฆ | K (100) |
| `id3` | strings `id0000000001`โฆ | N/K |
| `id4`, `id5` | integers | K |
| `id6` | integers | N/K |
| `v1`, `v2` | integers in 1โ5 and 1โ15 | |
| `v3` | a float in [0, 100) | |
The join tables are a left table `x` of N rows and three right tables of N/10โถ (`small`), N/10ยณ
(`medium`) and N rows (`big`), whose keys overlap 90% with `x`'s.
"""
nanuq """
As in db-benchmark's Polars scripts, both sides read the CSV files with the same schema
overrides and cast the string ids to `Categorical`. The scripts there first copy each table to
an Arrow IPC file and query that; here the queries scan the CSV files, so the timings include
reading them, as in the other benchmark chapters. Only the 10 million row, 100 group, no
missing values, unsorted variant is set up.
"""
nbText: """
The questions are in [`bench/dbbench.nim`](#src-bench-dbbench-nim)
and [`bench/dbbench.py`](#src-bench-dbbench-py).
When the book is built, each one runs on both sides on 10,000 rows, and the build checks that
the two tables are the same (sorted by their keys, so that the rows shown match).
"""let nimSource = readFile(".." / "bench" / "dbbench.nim")
let pySource = readFile(".." / "bench" / "dbbench.py")
proc pyKeys(keys: seq[string]): string = "[" & keys.mapIt(escapeJson(it)).join(", ") & "]"block:
let gfile = groupByFile(10_000)
let jdir = joinDir(10_000)
let x = scanGroupBy(gfile)
let t = scanJoin(jdir)
loadPython(gfile, jdir)
nbText: "## Group-by questions"for q in groupQs:
nbText: "### " & q.name & ": " & q.title
let nimSrc = sourcePart(nimSource, "proc " & q.name & "*", ["\nproc ", "\n# ---"])
let pySrc = sourcePart(pySource, "def " & q.name & "(", ["\n\n\ndef "])
nbRawHtml: queryTabs(nimSrc, pySrc, q.run(x).collect.sort(q.keys),
q.name & "(_x).collect().sort(" & pyKeys(q.keys) & ")")
nbText: "## Join questions"for q in joinQs:
nbText: "### " & q.name & ": " & q.title
let nimSrc = sourcePart(nimSource, "proc " & q.name & "*", ["\nproc ", "\n# ---"])
let pySrc = sourcePart(pySource, "def " & q.name & "(", ["\n\n\ndef "])
nbRawHtml: queryTabs(nimSrc, pySrc, q.run(t).collect.sort(["id1", "id2", "id3"]),
q.name & "(_t).collect().sort(['id1', 'id2', 'id3'])")
nanuq """
Nanuq spells a few things differently: keys go in a list (`on = ["id1"]`), `pl.sum("v1")` is
`col.v1.sum`, `** 2` is `.pow(2)`, and Python's `method="pearson"` is Nanuq's default `how`.
"""
nbText: """
## Running it on your machine
From the root of a clone of the book, with Nim, nimble, uv and git (the script installs the
book's dependencies first; the data goes to `bench-data/`, which git ignores; 10 million rows
are about 0.5 GB of group-by CSV and 0.7 GB of join CSV):
```sh
scripts/bench dbbench # 10 million rows, 3 timed runs per question
scripts/bench dbbench -d:benchRows=100000000 # 100 million rows
scripts/bench dbbench -d:benchLabel=my-laptop # a name for your machine
```
It writes the timings and the machine's specs to a timestamped file in `results/dbbench/`
and commits it; a pull request with that file adds a run to the tables at the top.
"""
nbSourceFiles:
nbFoldCode "bench/dbbench.nim"
nbFoldCode "bench/dbbench.py"
nbFoldCode "book/benchkit.nim", title = "`book/benchkit.nim`: timing, results and tables of the benchmark chapters"
nbFoldCode "scripts/bench", title = "`scripts/bench`: a full run on your machine"
bookSave()