One table per run of the full benchmark on someone's machine: for each query, the best of
the timed runs, in seconds, reading the CSV files included. A dash means the run did not
use that engine: older runs timed Nanuq with one engine only, and runs with Nanuq 0.2 have
13 queries, so compare totals only between runs with the same number of queries.
2026-10-31 (claude-sandbox), scale factor 1.0
Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, 16.9 GB, Linux 6.18.44-fc-v185. Nanuq 0.2.0, Polars 2.1.0, Nim 2.2.4.
Query
Nanuq in-memory
Nanuq streaming
Python in-memory
Python streaming
q1
2.13 s
-
0.76 s
0.71 s
q3
1.99 s
-
0.76 s
0.74 s
q4
1.98 s
-
0.79 s
0.70 s
q5
1.96 s
-
0.59 s
0.60 s
q6
1.94 s
-
0.53 s
0.53 s
q10
2.01 s
-
0.80 s
0.76 s
q11
0.33 s
-
0.11 s
0.09 s
q12
2.03 s
-
0.74 s
0.79 s
q15
1.94 s
-
0.55 s
0.60 s
q17
2.03 s
-
0.44 s
0.46 s
q18
2.51 s
-
0.73 s
0.94 s
q19
2.04 s
-
0.67 s
0.67 s
q21
4.44 s
-
1.44 s
1.44 s
total
27.32 s
-
8.90 s
9.03 s
2026-10-31 (pietro-mac), scale factor 1.0
Apple M3 Pro, 11 cores, 19.3 GB, macOS 15.7.3. Nanuq 0.2.0, Polars 2.1.0, Nim 2.2.5.
Query
Nanuq in-memory
Nanuq streaming
Python in-memory
Python streaming
q1
1.07 s
-
0.25 s
0.23 s
q3
1.02 s
-
0.23 s
0.25 s
q4
1.02 s
-
0.26 s
0.25 s
q5
1.01 s
-
0.21 s
0.22 s
q6
1.00 s
-
0.21 s
0.21 s
q10
1.02 s
-
0.24 s
0.24 s
q11
0.17 s
-
0.03 s
0.03 s
q12
1.02 s
-
0.27 s
0.27 s
q15
1.00 s
-
0.22 s
0.21 s
q17
1.00 s
-
0.18 s
0.18 s
q18
1.22 s
-
0.26 s
0.30 s
q19
1.02 s
-
0.27 s
0.28 s
q21
2.18 s
-
0.54 s
0.45 s
total
13.76 s
-
3.16 s
3.09 s
2026-11-02 (claude-sandbox), scale factor 1.0
Intel(R) Xeon(R) Processor @ 2.80GHz, 4 cores, 16.9 GB, Linux 6.18.44-fc-v185. Nanuq 0.6.0, Polars 2.1.0, Nim 2.2.4.
Query
Nanuq in-memory
Nanuq streaming
Python in-memory
Python streaming
q1
-
1.56 s
1.60 s
1.38 s
q2
-
0.21 s
0.14 s
0.14 s
q3
-
1.56 s
1.41 s
1.39 s
q4
-
1.45 s
1.37 s
1.21 s
q5
-
1.22 s
1.21 s
1.10 s
q6
-
1.43 s
1.15 s
1.17 s
q7
-
1.54 s
1.36 s
1.49 s
q8
-
1.46 s
1.20 s
1.30 s
q9
-
1.68 s
2.13 s
1.66 s
q10
-
1.61 s
1.51 s
1.37 s
q11
-
0.20 s
0.18 s
0.19 s
q12
-
1.83 s
1.64 s
1.51 s
q13
-
0.41 s
0.45 s
0.34 s
q14
-
1.38 s
1.19 s
1.20 s
q15
-
1.31 s
1.20 s
1.08 s
q16
-
0.18 s
0.18 s
0.16 s
q17
-
0.92 s
1.01 s
0.81 s
q18
-
1.80 s
1.43 s
1.74 s
q19
-
1.48 s
0.99 s
1.11 s
q20
-
1.47 s
1.29 s
1.36 s
q21
-
2.66 s
2.47 s
2.46 s
q22
-
0.22 s
0.20 s
0.19 s
total
-
27.61 s
25.31 s
24.36 s
2026-11-02 (pietro-mac), scale factor 1.0
Apple M3 Pro, 11 cores, 19.3 GB, macOS 15.7.3. Nanuq 0.6.0, Polars 2.1.0, Nim 2.2.5.
Query
Nanuq in-memory
Nanuq streaming
Python in-memory
Python streaming
q1
0.29 s
0.25 s
0.28 s
0.23 s
q2
0.03 s
0.03 s
0.03 s
0.03 s
q3
0.27 s
0.26 s
0.26 s
0.26 s
q4
0.27 s
0.25 s
0.27 s
0.24 s
q5
0.20 s
0.20 s
0.21 s
0.20 s
q6
0.22 s
0.21 s
0.21 s
0.23 s
q7
0.25 s
0.26 s
0.26 s
0.27 s
q8
0.22 s
0.22 s
0.23 s
0.22 s
q9
0.32 s
0.33 s
0.33 s
0.28 s
q10
0.25 s
0.24 s
0.23 s
0.23 s
q11
0.03 s
0.03 s
0.03 s
0.03 s
q12
0.31 s
0.30 s
0.29 s
0.31 s
q13
0.07 s
0.06 s
0.08 s
0.06 s
q14
0.25 s
0.23 s
0.24 s
0.22 s
q15
0.21 s
0.20 s
0.23 s
0.22 s
q16
0.03 s
0.03 s
0.03 s
0.03 s
q17
0.17 s
0.16 s
0.19 s
0.17 s
q18
0.24 s
0.30 s
0.24 s
0.29 s
q19
0.26 s
0.27 s
0.26 s
0.26 s
q20
0.28 s
0.25 s
0.28 s
0.25 s
q21
0.57 s
0.51 s
0.55 s
0.49 s
q22
0.04 s
0.03 s
0.04 s
0.04 s
total
4.78 s
4.61 s
4.76 s
4.55 s
How the tables are made
Each run of the full benchmark leaves a JSON file in
results/pdsh/, with
the machine, the versions and, for each engine and query, three timings. The tables above
are a Polars query over those files, so they come from the same tools as everything else
in this book.
The timings are two structs deep: engines, then queries. Two rounds of unnest and
unpivot turn each file into a long table with one row per engine and query, and
list.min keeps the best of the timed runs:
let index = @["date", "machine", "cpu", "nanuq", "scale"]
proc timings(path: string): DataFrame =
readJson(path)
.select(
col.timestamp.str.slice(0, 10).alias("date"),
col.label.alias("machine"),
col.system.struct.field("cpu"),
col.versions.struct.field("nanuqWrapper").alias("nanuq"),
col.params.struct.field("scaleFactor").alias("scale"),
col.timings)
.unnest("timings")
.unpivot(index = index, variableName = "engine", valueName = "queries")
.unnest("queries")
.unpivot(index = index & "engine", variableName = "query", valueName = "seconds")
let paths = sorted(toSeq(walkFiles("../results/pdsh/*.json")))
let times = concat(paths.mapIt(timings(it)), how = ConcatMethod.Vertical)
.withColumns(col.seconds.list.min)
nbShow times.head(3)
shape: (3, 8)
date
machine
cpu
nanuq
scale
engine
query
seconds
str
str
str
str
f64
str
str
f64
"2026-10-31"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2β¦
"0.2.0"
1.0
"nanuq in-memory"
"q1"
2.126872
"2026-10-31"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2β¦
"0.2.0"
1.0
"python in-memory"
"q1"
0.758044
"2026-10-31"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2β¦
"0.2.0"
1.0
"python streaming"
"q1"
0.707311
import glob
import polars as pl
index = ["date", "machine", "cpu", "nanuq", "scale"]
def timings(path):
return (
pl.read_json(path)
.select(
pl.col("timestamp").str.slice(0, 10).alias("date"),
pl.col("label").alias("machine"),
pl.col("system").struct.field("cpu"),
pl.col("versions").struct.field("nanuqWrapper").alias("nanuq"),
pl.col("params").struct.field("scaleFactor").alias("scale"),
"timings",
)
.unnest("timings")
.unpivot(index=index, variable_name="engine", value_name="queries")
.unnest("queries")
.unpivot(index=[*index, "engine"], variable_name="query", value_name="seconds")
)
times = pl.concat(
[timings(path) for path in sorted(glob.glob("../results/pdsh/*.json"))]
).with_columns(pl.col("seconds").list.min())
times.head(3)
shape: (3, 8)
date
machine
cpu
nanuq
scale
engine
query
seconds
str
str
str
str
f64
str
str
f64
"2026-10-31"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2β¦
"0.2.0"
1.0
"nanuq in-memory"
"q1"
2.126872
"2026-10-31"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2β¦
"0.2.0"
1.0
"python in-memory"
"q1"
0.758044
"2026-10-31"
"claude-sandbox"
"Intel(R) Xeon(R) Processor @ 2β¦
"0.2.0"
1.0
"python streaming"
"q1"
0.707311
Summing per run and engine, and a pivot with one column per engine, gives the total time
of each run:
nbShow times
.groupBy(index & "engine", maintainOrder = true)
.agg(len().alias("queries"), col.seconds.sum.round(2))
.pivot(on = "engine", index = index & "queries", values = "seconds", sortColumns = true)
TPC-H is the classic decision-support benchmark: eight
tables of a wholesale business (orders, line items, customers, suppliers, parts and the
nations and regions they are in) and 22 queries that report on them. Polars publishes
how fast it runs them as PDS-H, with its queries in
the polars-benchmark repository.
Nanuq 0.3 runs all 22. (Nanuq 0.2 ran 13 of them: the others need string functions or
the year of a date, which came with 0.3.)
The queries are in bench/pdsh.nim
and bench/pdsh.py.
When the book is built, each one runs on both sides on a small dataset (scale factor
0.01, about 10 MB of CSV), and the build checks that the two tables are the same.
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; scale factor 1 is about 1 GB of CSV):
scripts/bench pdsh # scale factor 1, 3 timed runs per query
scripts/bench pdsh -d:benchScale=10 # scale factor 10
scripts/bench pdsh -d:benchLabel=my-laptop # a name for your machine
It writes the timings and the machine's specs to a timestamped file in results/pdsh/
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.
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, pdsh
import ../foldcode
import std/[algorithm, os, json, strutils, osproc, sequtils]
bookInit()
const benchScale {.strdefine.} = "1"## scale factor of a full run (`-d:benchScale=10`)
nbText: "# PDS-H queries"
nanuq """
**About this chapter.** The queries are ported from the Polars queries of
[polars-benchmark](https://github.com/pola-rs/polars-benchmark), by the Polars
contributors, licensed under the
[Apache License 2.0](https://github.com/pietroppeter/nanuq-book/blob/main/licenses/polars-benchmark-Apache-2.0.txt).
The data comes from [tpchgen-cli](https://github.com/datafusion-contrib/tpchgen-rs), which
generates the TPC-H tables; it is made on the fly and never stored in the repository.
PDS-H is derived from TPC-H, but these results are not comparable to published TPC-H
results. The text is the book's own.
The code of the benchmark is folded under [Source files](#source-files), at the end.
"""proc tpchData(scale: string): string =
## The tables at this scale factor, generated with tpchgen-cli the first time.result = ".." / "bench-data" / "tpch-" & scale
ifnot fileExists(result / "lineitem.csv"):
createDir resultlet (o, code) = execCmdEx("tpchgen-cli csv -s " & scale & " --output-dir=" & quoteShell(result))
doAssert code == 0, "tpchgen-cli failed (run the book with `uv run`):\n" & o
typeQuery = tuple[n: int, run: proc (t: Tables): LazyFrame]
proc queries(scale: float): seq[Query] =
@[(1, q1), (2, q2), (3, q3), (4, q4), (5, q5), (6, q6), (7, q7), (8, q8), (9, q9),
(10, q10), (11, proc (t: Tables): LazyFrame = q11(t, scale)),
(12, q12), (13, q13), (14, q14), (15, q15), (16, q16), (17, q17), (18, q18),
(19, q19), (20, q20), (21, q21), (22, q22)]
proc pyCall(n: int, scale: float, engine = "in-memory"): string =
"q" & $n & "(**_tables" & (if n == 11: ", scale_factor=" & $scale else: "") &
").collect(engine=" & escapeJson(engine) & ")"proc loadPython(dir: string) =
discard runPython("import sys\nsys.path.insert(0, '../bench')\nfrom pdsh import *\n" &
"_tables = scan_tables(" & escapeJson(dir) & ")")
# --- A full run: only with -d:bench -------------------------------------------------whendefined(bench):
let scale = parseFloat(benchScale)
let dir = tpchData(benchScale)
let tables = scanTables(dir)
loadPython(dir)
var nimMemory, nimStreaming, pyMemory, pyStreaming = newJObject()
for (n, run) in queries(scale):
let q = "q" & $n
echo"[bench] ", q
nimMemory[q] = %timeIt(benchRuns, proc () = discard run(tables).collect(Engine.InMemory))
nimStreaming[q] = %timeIt(benchRuns, proc () = discard run(tables).collect(Engine.Streaming))
pyMemory[q] = %timePython(benchRuns, pyCall(n, scale))
pyStreaming[q] = %timePython(benchRuns, pyCall(n, scale, "streaming"))
discard saveResult("pdsh", %*{"scaleFactor": scale, "runs": benchRuns},
%*{"nanuq in-memory": nimMemory, "nanuq streaming": nimStreaming,
"python in-memory": pyMemory, "python streaming": pyStreaming})
# --- Results ----------------------------------------------------------------------
nbText: """
## Results
One table per run of the full benchmark on someone's machine: for each query, the best of
the timed runs, in seconds, reading the CSV files included. A dash means the run did not
use that engine: older runs timed Nanuq with one engine only, and runs with Nanuq 0.2 have
13 queries, so compare totals only between runs with the same number of queries.
"""
nbText: ""# the tables, filled in below from the Polars querylet summary = nb.blk.NbText
nbText: """
## How the tables are made
Each run of the full benchmark leaves a JSON file in
[`results/pdsh/`](https://github.com/pietroppeter/nanuq-book/tree/main/results/pdsh), with
the machine, the versions and, for each engine and query, three timings. The tables above
are a Polars query over those files, so they come from the same tools as everything else
in this book.
The timings are two structs deep: engines, then queries. Two rounds of `unnest` and
`unpivot` turn each file into a long table with one row per engine and query, and
`list.min` keeps the best of the timed runs:
"""
tabs """
import glob
import polars as pl
index = ["date", "machine", "cpu", "nanuq", "scale"]
def timings(path):
return (
pl.read_json(path)
.select(
pl.col("timestamp").str.slice(0, 10).alias("date"),
pl.col("label").alias("machine"),
pl.col("system").struct.field("cpu"),
pl.col("versions").struct.field("nanuqWrapper").alias("nanuq"),
pl.col("params").struct.field("scaleFactor").alias("scale"),
"timings",
)
.unnest("timings")
.unpivot(index=index, variable_name="engine", value_name="queries")
.unnest("queries")
.unpivot(index=[*index, "engine"], variable_name="query", value_name="seconds")
)
times = pl.concat(
[timings(path) for path in sorted(glob.glob("../results/pdsh/*.json"))]
).with_columns(pl.col("seconds").list.min())
times.head(3)
""":
nbCode:
let index = @["date", "machine", "cpu", "nanuq", "scale"]
proc timings(path: string): DataFrame =
readJson(path)
.select(
col.timestamp.str.slice(0, 10).alias("date"),
col.label.alias("machine"),
col.system.struct.field("cpu"),
col.versions.struct.field("nanuqWrapper").alias("nanuq"),
col.params.struct.field("scaleFactor").alias("scale"),
col.timings)
.unnest("timings")
.unpivot(index = index, variableName = "engine", valueName = "queries")
.unnest("queries")
.unpivot(index = index & "engine", variableName = "query", valueName = "seconds")
let paths = sorted(toSeq(walkFiles("../results/pdsh/*.json")))
let times = concat(paths.mapIt(timings(it)), how = ConcatMethod.Vertical)
.withColumns(col.seconds.list.min)
nbShow times.head(3)
nbText: """
Summing per run and engine, and a `pivot` with one column per engine, gives the total time
of each run:
"""
tabs """
(
times.group_by([*index, "engine"], maintain_order=True)
.agg(pl.len().alias("queries"), pl.col("seconds").sum().round(2))
.pivot(on="engine", index=[*index, "queries"], values="seconds", sort_columns=True)
)
""":
nbCode:
nbShow times
.groupBy(index & "engine", maintainOrder = true)
.agg(len().alias("queries"), col.seconds.sum.round(2))
.pivot(on = "engine", index = index & "queries", values = "seconds", sortColumns = true)
nbText: """
And query by query, on the latest run on an M3 Pro:
"""
tabs """
pl.Config.set_tbl_rows(22) # the default shows 10 rows
(
times.filter(pl.col("machine") == "pietro-mac")
.filter(pl.col("date") == pl.col("date").max())
.with_columns(pl.col("seconds").round(3))
.pivot(on="engine", index="query", values="seconds", sort_columns=True)
)
""":
nbCode:
let byQuery = times
.filter(col.machine == "pietro-mac")
.filter(col.date == col.date.max)
.withColumns(col.seconds.round(3))
.pivot(on = "engine", index = "query", values = "seconds", sortColumns = true)
nbRawHtml: byQuery.toHtml(maxRows = 22) # the default shows 10 rowsdiscard runPython("pl.Config.set_tbl_rows(10)")
const engines = ["nanuq in-memory", "nanuq streaming", "python in-memory", "python streaming"]
proc runTable(date, machine: string): string =
## The table of one run: every engine, a row per query and a row of totals.let cells = engines.mapIt(col.seconds.filter(col.engine == it).first.alias(it))
let run = times.filter(col.date == date and col.machine == machine)
.groupBy("query", maintainOrder = true).agg(cells)
# mean * count, not sum, which gives 0 for an engine the run did not uselet totals = run.select(@[lit("total").alias("query")] &
engines.mapIt((col(it).mean * col(it).count).alias(it)))
markdownTable(concat([run, totals]), boldLast = true)
for path in paths:
let run = readJson(path).select(
col.timestamp.str.slice(0, 10).alias("date"),
col.label.alias("machine"),
col.params.struct.field("scaleFactor").alias("scale"),
format("{}, {} cores, {} GB, {}. Nanuq {}, Polars {}, Nim {}.",
col.system.struct.field("cpu"), col.system.struct.field("cores"),
col.system.struct.field("memoryGB"), col.system.struct.field("os"),
col.versions.struct.field("nanuqWrapper"),
col.versions.struct.field("pythonPolars"),
col.versions.struct.field("nim")).alias("about"))
let (date, machine) = (run["date", 0, string], run["machine", 0, string])
summary.text.add "### " & date & " (" & machine & "), scale factor " &
$run["scale", 0, float] & "\n\n" & run["about", 0, string] & "\n\n" &
runTable(date, machine) & "\n"
nbText: """
## The benchmark
[TPC-H](https://www.tpc.org/tpch/) is the classic decision-support benchmark: eight
tables of a wholesale business (orders, line items, customers, suppliers, parts and the
nations and regions they are in) and 22 queries that report on them. Polars publishes
how fast it runs them as [PDS-H](https://pola.rs/posts/benchmarks/), with its queries in
the polars-benchmark repository.
Nanuq 0.3 runs all 22. (Nanuq 0.2 ran 13 of them: the others need string functions or
the year of a date, which came with 0.3.)
"""
nanuq """
The Python queries are the originals, unchanged; both sides read the CSV files with
`tryParseDates`, so the date columns are dates. In Nim, Python's `date(1995, 3, 15)` is
Nanuq's `date(1995, 3, 15)`, column names that Python passes as strings are `col(...)`,
keys are lists, `pl.len()` is the length of a column and `when/then/otherwise` is
`choose`. One query takes a detour for an expression Nanuq does not have yet: q20 takes the
unique keys with the frame's `unique` (no `Expr.unique`).
"""
nbText: """
The queries are in [`bench/pdsh.nim`](#src-bench-pdsh-nim)
and [`bench/pdsh.py`](#src-bench-pdsh-py).
When the book is built, each one runs on both sides on a small dataset (scale factor
0.01, about 10 MB of CSV), and the build checks that the two tables are the same.
"""let nimSource = readFile(".." / "bench" / "pdsh.nim")
let pySource = readFile(".." / "bench" / "pdsh.py")
block:
let dir = tpchData("0.01")
let tables = scanTables(dir)
loadPython(dir)
for (n, run) in queries(0.01):
nbText: "## Q" & $n
let nimSrc = sourcePart(nimSource, "proc q" & $n & "*", ["\nproc "])
let pySrc = sourcePart(pySource, "def q" & $n & "(", ["\n\n\ndef "])
nbRawHtml: queryTabs(nimSrc, pySrc, run(tables).collect, pyCall(n, 0.01))
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; scale factor 1 is about 1 GB of CSV):
```sh
scripts/bench pdsh # scale factor 1, 3 timed runs per query
scripts/bench pdsh -d:benchScale=10 # scale factor 10
scripts/bench pdsh -d:benchLabel=my-laptop # a name for your machine
```
It writes the timings and the machine's specs to a timestamped file in `results/pdsh/`
and commits it; a pull request with that file adds a run to the tables at the top.
"""
nbSourceFiles:
nbFoldCode "bench/pdsh.nim"
nbFoldCode "bench/pdsh.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()