By Nanuq 0.6 a CI run took about fifteen minutes, and it got longer with every release. None of that time went into anything heavy: the Rust library comes from a cache or a release, the explainers read committed data, and the benchmark chapters of the book read result files. The time went into the toolchain doing the same work over and over. Two changes brought a run down to about two and a half minutes: one program per suite instead of one binary per file, and a faster linker. This post shows where the time went, what changed, and what it costs. It is also a note for anyone wrapping a big static library for Nim: link time is the first thing to measure.
Where fifteen minutes went↑ contents
Every test file, every spec's examples and every page of this site was its own binary.
Each one compiled Nanuq again and linked libnanuq_ffi.a, the static Polars wrapper,
which is about 310 MB. With GNU ld that link takes about 9 seconds of a 12-second
compile, every time. Main run #175 (2 November) broke down like this:
| Job | Step | Time | Programs |
|---|---|---|---|
| test | the test files, nim r each |
6m45s | 45 |
| test | the spec examples, one program per spec | 5m56s | 47 |
| test | nimble install, the moto venv |
1m05s | |
| docs | the pages, nim r each |
2m57s | 16 |
| docs | nimble install (nimib, ggplotnim, plotly) |
1m26s |
The book had the same shape: about fifty chapters, one binary each, and a full build (every Nanuq pin bump) took 6m54s. Its pull requests were already fast, because since book PR #5 only the chapters whose inputs changed are rebuilt.
The linker↑ contents
Timing the link of one test binary by itself, with the same objects each time:
| Linker | Time |
|---|---|
| GNU ld (default) | 9.2 s |
GNU ld, --strip-debug |
8.6 s |
| gold | 3.2 s |
| lld | 3.3 s |
gold, --strip-debug |
3.9 s |
lld, --strip-debug |
0.7 s |
config.nims now passes -fuse-ld=lld -Wl,--strip-debug on Linux when ld.lld is
installed, and CI makes sure it is. That alone took the
45 test files from 9m32s to 4m22s on a 4-core machine. It only affects builds in this
repository: config.nims doesn't ship with the package, so users of Nanuq link as
before.
One program per suite↑ contents
The bigger win came from not building 45 programs at all. Nim runs the top-level code
of every imported module when the program starts, in import order. So a module that
imports every test file runs every unittest suite, one after the other, and none of
the test files has to change. tests/all.nim finds them at compile time (simplified):
macro importTests(): untyped =
let dir = currentSourcePath().parentDir
var src = ""
for name in sortedTestNames(dir): # tests/test_*.nim, from `ls`
# absolute: parseStmt has no file to be relative to
src.add "import \"" & dir / name & "\"\n"
result = parseStmt(src)
importTests()
Files that need an optional package (Datamancer, Arraymancer, db_connector) go in only
when (compiles do: import datamancer) holds, the same check nimib's moduleAvailable
uses. A single file still runs on its own, as nim r tests/test_csv.nim, and unittest
filters work on the whole suite: nim r tests/all.nim "csv::*".
The same trick renders this site. docs/all.nim imports every post, then the index,
the coverage map and the OpenSpec page. Each page renders when its module is
initialised, and all 16 came out byte-identical to the page-by-page build. One thing
did need care: display options are global, and four posts call setConfig. So
useDevlogPost now starts every post with resetConfig().
The spec examples went one step further, and became tests. tests/specsuite.nim reads
openspec/specs/*/spec.md at compile time and turns every example into a unittest
test named after its spec and line. What the example prints is captured at the file
descriptor, so output from the Rust side counts too, and it is compared with the
example's text block. The examples were always meant to be guaranteed to work. Now they
fail like any other test. Specs that import Arraymancer or Datamancer get files of their
own, because their names clash with the others' (quantile is defined in both).
The numbers↑ contents
Measured locally (4 cores, cold cache) and on pull request runs of nanuq#67:
| What | Before | After |
|---|---|---|
| tests, 45 files (local) | 9m32s | 47 s |
| spec examples, 224 (local) | 6m00s | 35 s |
| tests + spec examples, 684 tests (local) | 15m32s | 70 s |
| site, 16 pages (local) | 4m46s | 1m25s |
| CI test job | 14m05s | 1m16s |
CI docs job (~/.nimble now cached too) |
4m45s | 1m47s |
| book full build, CI (lld only) | 6m54s | 5m29s |
| book full build, one program (local) | 8m25s | 71 s |
| book full build, one program (CI) | 6m54s | 76 s |
The book gained less from the linker alone. Its chapters run Python too (the other half of each tab), so linking was a smaller share of their time. One program helped there as well, next section.
The book, as one program↑ contents
The book keeps a record of what each chapter read, so a pull request rebuilds only the
chapters whose inputs changed. The record has two halves: the files Nim compiled (from
-d:nimBetterRun) and the files the chapter opened at run time (from strace). A
single program for every chapter would merge both, and that is what made it look like a
separate design. It turned out to need little:
bookbuild.nimwrites a program that imports the stale chapters, in book order, and runs it once under strace.- The trace splits cleanly. Each chapter starts by reading its own source file, because
nbInitdoes, so every open from there to the next chapter's source belongs to it. - The compile half is the program's file list minus the other chapters' sources.
- A chapter that fails, or a program that doesn't compile, sends the chapters not yet finished back to the old path, one program each, so the failing one still gets its own log.
Chapters share more state than posts do, and three kinds of it mattered: the display
options of Nanuq and Polars, the Python namespace, and the working directory, which
nbInit changes. bookInit and bookSave now reset all three. One chapter shows the
codes behind categorical values, and those depend on every string Polars has seen in
the process, so it keeps a program of its own. To check the rest, every page of a
shared build was compared with a page-by-page build. The only differences were ones
that also show up between two page-by-page builds: the row order of a Python
group_by without maintain_order, object addresses, cache ids.
A full build, which every Nanuq pin bump triggers, went from 505 seconds to 71 locally (book PR #13): 26 seconds to compile all 56 chapters at once, 13 to run them. On CI the whole build step took 76 seconds, against 6m54s before this work. With the 18 chapters of book PR #12 on top, all 75 build in 82 seconds locally.
Why nimib doesn't mind↑ contents
nimib was never meant to have many documents in one program, yet the site and the book
needed no changes to their pages. It helps to see what the macro in docs/all.nim
actually expands to. With today's posts it is this, and nothing more:
import "/…/docs/blog/above_4000"
import "/…/docs/blog/aged_19"
# … one line per post, in file-name order …
import "/…/docs/blog/two_minute_ci"
import "/…/docs/index"
import "/…/docs/polars_coverage"
import "/…/docs/openspec"
No nbInit appears in all.nim, and no page's code is pasted into it. Each import
compiles a page as a module of its own, from its own file, exactly as nim r on that
page would. That is where nbInit, a template, expands. In move_37.nim it becomes
roughly:
var nb: Nb # a top-level variable of module move_37, not exported
nb.doc.initDir = getCurrentDir()
nb.doc.thisFile = "/…/docs/blog/move_37.nim" # instantiationInfo, fixed at compile time
nb.doc.source = readFile(nb.doc.thisFile)
# …
two_minute_ci.nim gets its own var nb, with its own path baked in, and the two
never see each other. When the program starts, Nim runs each module's top-level code
once, in import order: all of above_4000 (nbInit, its blocks, nbSave), then all
of aged_19, and so on. What is concatenated is the execution, not the source. Pasting
the pages into one file, or include-ing them, would break: the second var nb is a redefinition, and every page would think it is all.nim.
Code blocks follow the same pattern: they quote their code by reading the file named in
the block's line info, so they quote the right page. One thing is shared, though: the
renderer. nbInit sets nb.backend = nbToHtml, and NbRender is a ref, so every page
holds the same renderer, and a theme that changes a partial changes it for the pages
after it too. Here every page applies the same theme, which sets the same partials, so
nothing leaks. A site that mixes themes in one program would need each theme to set all
the partials it relies on.
The known trouble with many nimib pages comes from moving nbInit away from the page. Called
from a helper in another file, instantiationInfo names the helper's file, and the page
gets the wrong source and name. That is why nbInit takes thisFileRel, and why
nimibook needs it for Markdown chapters. Wrapping a page in a proc fails for another
reason: Nim allows import only at the top level. Importing whole modules avoids both.
What doesn't stay per page is process state: the working directory (nbInit moves to
homeDir, so the next page starts there), command-line options (every page parses the
same ones, so --nbFilename would name them all alike), and whatever globals the
page's own code touches, as above.
What it costs↑ contents
One thing, and a warning.
A warning on the edit loop. Running a single file works as before, and is as fast as before. Running the whole suite after changing one file recompiles all of it, about 26 seconds. So when working on one file, run that file.
Debug info. --strip-debug drops the DWARF sections of the binary, almost all of
which belong to the Polars library. What stays: Nim's own stack traces, which don't use
DWARF, and the symbol table, so a Rust panic backtrace still names its functions. What
goes: file and line numbers in those backtraces, and stepping through Polars source in
gdb or lldb. We have not needed either yet. When we do, -d:nanuqKeepDebugInfo brings
them back for that build. It is the right trade for a test suite that is built far
more often than it is debugged.
Source files↑ contents
Every source file this page mentions, folded: tap one to read it. A file's name in the text leads here.
config.nims: lld, when it is there 10 lines
# Lets `nim r examples/...` and `nim r tests/...` find the package from the repo.
switch("path", thisDir() & "/src")
# Linking the static Polars library (~300 MB) is most of a build: GNU ld takes ~9 s per
# binary, lld ~0.7 s once the debug info (only the library's, Nim's stack traces don't
# use it) is left out. Used when lld is installed (Linux only; macOS's linker is fast).
when defined(linux) and not defined(nanuqKeepDebugInfo):
if findExe("ld.lld").len > 0:
switch("passL", "-fuse-ld=lld")
switch("passL", "-Wl,--strip-debug")config.nims
docs/all.nim: the whole site in one program 27 lines
## Renders the whole site in one program: every dev-log post (docs/blog/*.nim), then
## the index, the Polars coverage map and the OpenSpec page. One compile and one link
## instead of one per page.
##
## nim r docs/all.nim # the whole site
## nim r docs/blog/move_37.nim # one post, as before
##
## Each page renders when its module is initialised, in import order: posts by file
## name, then the index (it checks the rendered posts), coverage and OpenSpec pages.
## Posts are found at compile time, so a new one needs no list here.
import std/[macros, os, strutils, algorithm]
macro importPages(): untyped =
let dir = currentSourcePath().parentDir
var posts: seq[string]
for line in staticExec("ls " & quoteShell(dir / "blog")).splitLines:
if line.endsWith(".nim"): posts.add line[0 ..< ^4]
posts.sort
var src = ""
# absolute paths: parseStmt has no file to be relative to
for p in posts: src.add "import \"" & dir / "blog" / p & "\"\n"
for p in ["index", "polars_coverage", "openspec"]: src.add "import \"" & dir / p & "\"\n"
result = parseStmt(src)
{.warning[UnusedImport]: off.}
importPages()docs/all.nim
tests/all.nim: every test file in one program 40 lines
## Runs every test file (tests/test_*.nim) in one program: one compile, one link.
## That includes the examples in openspec/specs (test_specs*.nim, see specsuite.nim).
##
## nim r tests/all.nim # all tests
## nim r tests/all.nim "csv::*" # unittest filters work as usual
## nim r tests/test_csv.nim # a single file, as before
##
## Test files are found at compile time, so a new one needs no list. Each file's suites
## run when its module is initialised, in file-name order. Files that need an optional
## package (Datamancer, Arraymancer, db_connector) are left out when it is not installed.
import std/[macros, os, strutils, algorithm]
const optional = [("test_datamancer", "datamancer"), ("test_arraymancer", "arraymancer"),
("test_database", "db_connector/db_sqlite"),
("test_specs_datamancer", "datamancer"),
("test_specs_arraymancer", "arraymancer"),
("test_specs_database", "db_connector/db_sqlite")]
macro importTests(): untyped =
let dir = currentSourcePath().parentDir
var names: seq[string]
for line in staticExec("ls " & quoteShell(dir)).splitLines:
if line.startsWith("test_") and line.endsWith(".nim"): names.add line[0 ..< ^4]
names.sort
var src = ""
for name in names:
var needs = ""
for (t, m) in optional:
if t == name: needs = m
let imp = "import \"" & dir / name & "\"\n" # absolute: parseStmt has no file to be relative to
if needs.len == 0:
src.add imp
else: # the check nimib's moduleAvailable does
src.add "when (compiles do: import " & needs & "): " & imp &
"else: {.hint: \"tests/all.nim: skipping " & name & " (needs " & needs & ")\".}\n"
result = parseStmt(src)
{.warning[UnusedImport]: off.}
importTests()tests/all.nim
tests/specsuite.nim: the spec examples as tests 59 lines
## The Nim examples in openspec/specs as unittest tests: each ```nim block is a test
## (named `<capability>:<line>`), and when a ```text block follows it, what the example
## prints must equal it. Used by tests/test_specs*.nim; tools/specexamples.nim checks
## the same examples on its own and can `--update` the expected output.
##
## What an example prints is captured at the file descriptor, so output from Polars
## (Rust) counts too.
import std/[macros, os, strutils, algorithm, posix, unittest]
import ../tools/specexamples
const specRoot = currentSourcePath().parentDir.parentDir / "openspec" / "specs"
type Capture* = tuple[saved: cint, path: string]
proc startCapture*(): Capture =
flushFile stdout
result.path = getTempDir() / "nanuq-spec-" & $getpid() & ".txt"
let f = open(result.path, fmWrite)
result.saved = dup(1)
discard dup2(f.getFileHandle, 1)
f.close
proc stopCapture*(c: Capture): string =
flushFile stdout
discard dup2(c.saved, 1)
discard close(c.saved)
result = readFile(c.path).strip(leading = false)
removeFile c.path
macro specTests*(only: static string = ""): untyped =
## The examples of every spec that needs no other package, or with `only`, of that
## one capability (a spec that imports Arraymancer, Datamancer or db_connector).
var caps: seq[string]
for line in staticExec("ls " & quoteShell(specRoot)).splitLines:
if line.len > 0 and fileExists(specRoot / line / "spec.md"): caps.add line
caps.sort
var imports: seq[string]
var body = ""
for cap in caps:
let spec = Spec(cap: cap, exs: parseExamples(staticRead(specRoot / cap / "spec.md").splitLines))
if spec.exs.len == 0: continue
if (only.len > 0 and cap != only) or (only.len == 0 and spec.ownProgram): continue
body.add "suite " & escape("spec " & cap) & ":\n"
for ex in spec.exs:
body.add " test " & escape(cap & ":" & $ex.line) & ":\n"
body.add " let capture = startCapture()\n try:\n block:\n"
for l in ex.code:
if l.startsWith("import "):
if l notin imports: imports.add l
else: body.add " " & l & "\n"
body.add " discard\n"
body.add " finally:\n let printed = capture.stopCapture\n"
if ex.outFirst >= 0:
body.add " check printed == " & escape(ex.expected.strip(leading = false)) & "\n"
else:
body.add " discard printed\n"
result = parseStmt("import nanuq, nanuq/datasets, std/[options, os, strutils]\n" &
imports.join("\n") & "\n" & body)tests/specsuite.nim