Skip to content
kixel-aiPublic

About

Rust benchmarks counted under stock Valgrind and timed in pairs

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

swole

Measures each benchmark in one of three modes over the same compiled benchmark targets, and writes the measures as Kixel Quest's metrics.json, or compares a base commit with the working tree:

  • swole sim, what gates a merge, counts its instructions and simulates its caches and branches under stock Valgrind, one Valgrind process a job, in parallel across the host's cores, the same on any x86_64 Linux host that shares its fingerprint: hosted CI, a self-hosted runner, or an agent's own, with no third-party service in the loop. It replaces CodSpeed's runner over the benchmarks as they are written for it.
  • swole quick, an agent's local spot-check, counts them natively, once each (and with <base>, again for each noise floor), with the host's Linux perf counters, 20 to 50 times faster, and comparable only on hosts like this one.
  • swole bench, what gates a release, times them by wall clock on any Linux or macOS host, alone or paired with a base commit's, beside what each process used and every perf counter the host's capabilities allow.

Each mode also counts each harness benchmark's heap allocations, with no privilege, in a pass of its own.

Benchmarks are plain #[bench] functions written with its harness, or for sim, CodSpeed's compatibility crates.

Three crates:

  • swole, the harness a benchmark target puts in its [dev-dependencies];
  • swole-macros, its #[bench] attribute;
  • cargo-swole, the runner, installed as both swole and cargo swole.
cargo install --locked cargo-swole
# Or run it from Nix, pinning a revision with github:kixel-ai/swole/<rev>:
nix run github:kixel-ai/swole -- sim --out metrics.json

Use a runner and harness from the same release: the runner refuses a harness whose crate version differs from its own, and cargo install --locked cargo-swole@<version> pins one. A Git or Nix build of a revision pairs with the harness at that same revision, since two revisions sharing a version pass the check. With a Cargo install, put Valgrind 3.20 or later on PATH for sim and inspect, and objdump for inspect.

The commands below show usage with swole harness targets. CodSpeed targets execute their benchmarks during discovery, including swole list. Run swole --help for the installed runner's full command and option list.

swole sim [<base>] [--benchmarks <file> [--allow-missing]] [--out metrics.json] [--report <file>] [--jobs <n>] [--no-cache] [-- <cargo bench args>]
swole quick [<base>] [--benchmarks <file> [--allow-missing]] [--out metrics.json] [--report <file>] [--jobs <n>] [--no-cache] [-- <cargo bench args>]
swole bench [<base>] [--benchmarks <file>] [--out metrics.json] [--report <file>] [-- <cargo bench args>]
swole inspect <benchmark> [<base>] [-- <cargo bench args>]
swole bisect <good> <bad> [--mode quick|sim] [--benchmarks <file>] [--jobs <n>] [-- <cargo bench args>]
swole list [-- <cargo bench args>]   # each benchmark's name a line, as --benchmarks reads them, none run
swole fingerprint sim|quick|bench

With <base>, a commit, each mode measures <base> as well as the working tree and prints each change, as Compare says; --out is then bench's alone, and --allow-missing none's.

cargo swole <command> is the same as swole <command>.

What it counts

swole sim counts, in a Cargo workspace, its benchmark targets, written with swole or with CodSpeed's compatibility crates (codspeed-criterion-compat 6); quick and bench measure only swole's. It builds them once with --cfg codspeed, which CodSpeed's crates take, as cargo codspeed build does, passing any arguments after -- to Cargo, such as -p moq-net --bench varint. Every mode builds with the same flags, so switching between them recompiles nothing: --remap-path-prefix=<workspace>=${workspace}, so a binary's bytes and debuginfo do not move with the checkout's path (a path outside the workspace, such as a registry's under Cargo's home, and one a build script bakes in with env!, still do), then the environment's rustflags, which a remap of their own overrides, then the cfg and -Cdebuginfo=limited -Cstrip=none, which keep the symbols and line tables sim and bench attribute costs by whatever the Cargo profile or the environment strips, and so override the environment's own -Cdebuginfo and -Cstrip. The name is the one mbx's share_workspace_root gives the workspace, so a host with it and one without build the same bytes. Cargo takes rustflags from one source and ignores the rest, so these join the first that sets any: CARGO_ENCODED_RUSTFLAGS, RUSTFLAGS, or else what Cargo's configuration gives the build, which swole asks Cargo for rather than merging itself: where a config file, CARGO_BUILD_RUSTFLAGS, or CARGO_TARGET_<TRIPLE>_RUSTFLAGS sets rustflags, one cargo check of a throwaway crate in the build directory, with the build's --configs and --targets, reports what Cargo hands its build script for each target (its CARGO_ENCODED_RUSTFLAGS, CARGO_CFG_TARGET_FEATURE, and RUSTC), so the files, their includes, cfg() keys, the environment's keys, build.target, and each --config resolve as Cargo resolves them, whichever Cargo the toolchain pins. It costs a fraction of a second (0.1 to 0.4 s measured), only where rustflags are set. A configured -C link-arg=-fuse-ld=mold passes through, whole, and the crate's build script links with the flags the real build's own would, so a flag Cargo cannot build with fails the probe as it fails the build. The probe links its build script with those flags from a scratch directory, so a flag that names a file relative to the workspace (-C link-arg=./extra.o) fails it where the build would not; give such a path absolutely. An @file of rustflags is refused, since the fingerprint cannot see inside it. A build whose targets get different flags is refused, since one set goes to every target, as is the unstable host config's rustflags, which swole would not merge. Where nothing sets rustflags, these are the only flags. Each target lists its benchmarks first: a harness target by evaluating their args without running a setup or a call (SWOLE_LIST=1), one of CodSpeed's crates by running each once natively. swole runs a harness target only when the swole it was built with, whose version its listing prints, comes from swole's own release, and the harness refuses a swole of any other, which passes its version in SWOLE_VERSION: either fails before measuring anything, naming both versions and how to align them, since what the two say to each other changes in any release. Then each benchmark runs alone in its own Valgrind process, through the harness's SWOLE_BENCH or CodSpeed's CODSPEED_ISOLATED_BENCHMARK. A target that runs no benchmark through either, such as one whose #[bench]es are all compiled out on the host or have empty args, a plain main, or one of CodSpeed's whose every benchmark CodSpeed skips, such as one of only iter_custom's, adds none, and swole names it on stderr; a run left with no benchmark at all fails. One that runs some through both fails the run: leave it out with --bench. It builds them with cargo bench, with itself as the targets' runner, which records how Cargo launches each target, its directory and whole environment ([env], CARGO_MANIFEST_DIR, the library path), instead of running it; every listing and count launches the target the same way. Those records live in a directory only the user can read, removed once read. A runner a config or the environment sets, for any target, fails the run before anything builds, as does, once built, an [env] that sets GLIBC_TUNABLES, which the fingerprint reads from the environment, and an argument for the targets after Cargo's own --, which neither harness takes: --benchmarks chooses benchmarks. Every count, like the fingerprint, runs the Valgrind on swole's own PATH, whatever PATH a target gets.

Elsewhere, sim counts the programs --program names, each a shell command whose program brackets its benchmarks itself, with swole's harness or CodSpeed's instrument hooks, after --build's command builds them. Each program is one Valgrind process, which follows each exec, so a command may go through a shell or just. just ffi count counts rust2's binding benchmark this way.

Each benchmark is the Callgrind dump its hooks name after it, between ZERO_STATS and START_INSTRUMENTATION before it and STOP_INSTRUMENTATION and DUMP_STATS_AT after it, with Valgrind's --instr-atstart=no, so nothing outside a benchmark counts. Its count is the dump's totals in Ir, instructions executed, on every thread, beside its simulated cycles. The run fails on a dump with an unknown trigger, a benchmark without totals or with zero instructions, two benchmarks of one name, a job that fails, and a name --benchmarks lists that no benchmark has, so a bisect step never reads a suspect it could not count as clean. With --allow-missing, sim or quick instead names each such name on stderr, and in the job summary under GitHub Actions, counts the rest, and fails only when none is there: a bisect step at a commit before a suspect was added, or after a rename, keeps its other suspects' counts, and Kixel Quest reads one metrics.json lacks as unmeasured. rust2's Valgrind workflow passes it with the benchmarks a bisect dispatches it with. A compare fails on such a name only when neither side has it, since a change may add or remove a benchmark. A program's benchmarks all run even when --benchmarks names only some; a Cargo benchmark runs only when named. A dump named Metadata: ... is the hooks' own description of their integration, never a benchmark, so no benchmark may take a name with that prefix: it would go uncounted.

A harness benchmark beside which the process had another thread, one there when its call started or ended, or one its call started, which the preload sees even when it is gone by the call's end, counts what that thread ran meanwhile, which the scheduler decides. So sim counts each such benchmark's job five times in all, and records the median of the five, with their least and most beside it, marked sampled (~): for every measure, its instructions, cache misses, branch mispredicts, and estimated cycles alike, in the tables and as lower and upper in --report, and for the instructions and estimated cycles, as lower_value and upper_value in metrics.json. So does every benchmark whose threads swole cannot see: those of CodSpeed's crates and of a --program, whose harness runs every benchmark in one process. A harness benchmark that ran alone counts once: under the preload's randomness and clock it repeats exactly, but for an input the host decides, such as the order a directory lists its entries in, which no repeat on one host would show.

The instrument hooks' ADD_DESC after each benchmark, a request only CodSpeed's Valgrind fork knows, leaves an unknown callgrind client request warning in the job's Valgrind log, under target/swole/jobs-*, beside its profiles and output. Each run takes a directory of its own there, so runs in one tree never read each other's profiles, and removes it when it succeeds; a failed run keeps it and names it.

Simulated cycles

An instruction count misses what costs a real core most: data laid out so it misses the cache, and branches it cannot predict. So every count also runs Callgrind's cache and branch simulation (--cache-sim=yes --branch-sim=yes), with its caches sized outright, as CodSpeed's runner sizes them, rather than from the host's CPUID: a 32 KiB, 8-way first level for instructions (--I1=32768,8,64) and one for data (--D1=32768,8,64), and an 8 MiB, 16-way last level (--LL=8388608,16,64), each of 64-byte lines. Valgrind runs with --command-line-only=yes, so a .valgrindrc or VALGRIND_OPTS, which could turn on its hardware prefetch model, never changes a count behind the fingerprint's back. Each benchmark reports Callgrind's every event:

event measure
Ir instructions
Dr, Dw data reads, data writes
I1mr, D1mr, D1mw I1 misses, D1 read misses, D1 write misses
ILmr, DLmr, DLmw LL instruction misses, LL read misses, LL write misses
Bc, Bcm conditional branches, conditional mispredicts
Bi, Bim indirect branches, indirect mispredicts

and from them, its estimated cycles: a cycle an instruction, 10 more for each first-level miss, which the last level serves, 100 more for each last-level miss, which memory serves, and 20 more for each mispredicted branch, whose work the core throws away:

estimated cycles = Ir + 10 (I1mr + D1mr + D1mw) + 100 (ILmr + DLmr + DLmw) + 20 (Bcm + Bim)

The weights are KCachegrind's classic cycle estimate's, which CodSpeed's documentation describes too, plus a mispredict's typical penalty. They model no real core, so a change of a few percent says where to look rather than what a host will time: bench times. But the simulation is deterministic, so a benchmark that runs alone repeats its every event exactly, as it does its instructions, and two layouts or branch patterns that run the same instructions part clearly. Simulating takes Callgrind two to three times as long as counting alone: 2.2 times, 5.5 s to 12.3 s, on a debug build's loop of 20 million loads and stores.

Callgrind stays the simulator because no alternative beats it by enough. A prototype QEMU TCG plugin measured slower than Callgrind on moq's benchmarks, and a DynamoRIO client is estimated at about 3 times as fast at best. Both would count at addresses the host kernel picks, so their misses would stop repeating across hosts. docs/sim-backends.md records the numbers.

Randomness and the clock

A count follows everything before it in the process, down to the allocator's state, so a seed or a clock read that differs from run to run moves it. So every process a job runs preloads a library, preload.rs, built with swole and kept under ~/.cache/swole (or $XDG_CACHE_HOME), which replaces glibc's:

  • randomness (getrandom, getentropy, and syscall(SYS_getrandom)) with one fixed-seed stream, the same in every process, so std's HashMap seeds and the getrandom crate's bytes repeat;
  • every clock (clock_gettime, gettimeofday, time) with one that starts at the same instant in every process, a day of uptime and 2026-01-01 on the wall, and advances 1 µs a read;
  • pthread_create with one that also counts the threads the process started, which the harness reads around each call;
  • and timed waits (epoll_wait, poll, nanosleep, clock_nanosleep, a timed condition variable, futex, semaphore, mutex or rwlock lock, thread join, or message queue call) with ones that still wait as long as they ask, on the host's clock, and move this clock by what they waited when they expire. A timer armed at an absolute time (timerfd_settime or timer_settime with its ABSTIME flag) aborts the process, naming the call in its Valgrind log, since the kernel would read the deadline on the host's clock.

Each process logs that it loaded the library to its Valgrind log, and a process that measured a benchmark without it fails the run: a static executable never loads it, nor does one whose environment drops LD_PRELOAD. A process that reaches the kernel without glibc, as Go's runtime does, reads the host's randomness and clock for what it does so. Load still decides whether a real timeout or I/O comes first, so a benchmark that races them can still move.

Paths and the environment

The same binary counts differently when its process starts with a longer path or a larger environment, since both sit on the initial stack and in the heap, and move the addresses, and so the copy loop glibc picks, after them. So every job's arguments and environment are padded to 1 MiB with SWOLE_PAD_00 to _15, which puts its initial stack at the same place however long its checkout's path or however large the host's environment, such as CI's GITHUB_REF on another branch. A job whose own take more fails the run, as does a stack limit under 4.25 MiB (ulimit -s 4352), since Linux takes a quarter of it for them. A --program job pads its shell's launch: the program the shell runs keeps that environment but gets its own arguments, so a command that expands a checkout's path, such as "$PWD/target/probe", still moves with that path's length. And CodSpeed's crates get their workspace relative to its Git repository, from which they name each benchmark's file, so they never resolve the checkout's path; a benchmark package at the repository's root still does, as does every benchmark outside a repository, which CodSpeed names by its absolute path, so their counts still move with that path's length. A path a build compiles in, such as a panic's location in a dependency outside the workspace, is the build's to keep fixed across checkouts; a compare counts both its sides from one directory, so it never moves between them.

What a benchmark reads

A count also follows the variables a benchmark reads, and the files: rind's aws-lc picks its code by OPENSSL_ia32cap, and a build script that reruns on a variable can build another library. Hashing the host's whole environment would give every host its own series, since PATH, HOME, and the user differ; clearing it would break a benchmark that reads a variable on purpose. So swole hashes what each benchmark reads:

  • at run time, each variable its processes look up through glibc's getenv or secure_getenv, set or not, by the hash of each value it had, which the preload records as the lookup returns and writes out as the process exits;
  • and at build time, each variable env! or option_env! read in any unit the build compiled, as rustc's dep-info records it, and each a build script reruns on (cargo::rerun-if-env-changed, or cargo:), set or not, found from the units Cargo's JSON messages report. Those messages say nothing of which unit another depends on, so every variable the build read is every benchmark's. A Cargo config's [env] setting one a build script reruns on fails the build, since Cargo's precedence decides what the script saw: export it instead.
  • and at run time, each path the host owns that its processes open, stat, list, or resolve, by the call, the error it found, and a link's target, so a library that checks for a path before it picks a code path, such as aws-lc enabling its snapshot-safety check when /dev/sysgenid exists, counts in a series of its own on a host where the path differs.

The variables swole's harness or launch sets, and those Cargo sets for a build or a launch (SWOLE_, CODSPEED_, CARGO_, OUT_DIR, LD_PRELOAD, and the TARGET, PROFILE, and the like it gives each build script), which name where the checkout is or how Cargo built it, are left out. A benchmark that read any has its series name the hash beside the fingerprint, such as instructions (x86_64-3059cd1d9e65 env 1a2b3c4d), so one whose variable takes another value, or that starts reading one, counts in a series of its own while every other keeps its own. A compare counts both sides under one environment, so it still ranks such a change, marked environment changed. --report names each benchmark's hash (env, and base_env when the base's differs), the variables it read (variables, and build_variables by name alone, since a value may be a secret), and each path it read (files), relative to the directory swole runs in when under it. The paths that enter the hash are among them: those not under the directory or the build, nor left out below.

The path hash has three limits, each a read that can change a count while the hash stays put:

  • the temporary directories (/tmp, /var/tmp, /dev/shm, and $TMPDIR) are left out whole, since a setup names its scratch files afresh each run and the preload cannot tell those from a host marker there, so a setup that picks its workload by a host-made file such as /dev/shm/feed-ready is not told apart;
  • a path with a .. is named where it lands, so a host-managed link that redirects a probe into the checkout, as /opt/bench/current/../feature.toml through a current link that switches between two checkout directories, leaves the hash when the landing is the checkout's;
  • and a .. after a directory that is gone is taken as spelled, so with only /srv/app/cpu installed, a probe of /srv/app/cpu/../bench.conf and one of /srv/app/gpu/../bench.conf both hash as /srv/app/bench.conf, and swapping which backend is installed swaps their results unseen.

The preload records each path a process opens, stats, lists, or resolves (open, openat, fopen, opendir, fdopendir, stat, lstat, fstatat, statx, readlink, readlinkat, access, faccessat, and realpath, with their 64 and fortified forms), with the error it found, if any, and a link's target, relative to the directory swole runs in when under it; a process's look at itself, under /proc/self, is left out. A read inside a measured call costs instructions that move with the host: glibc's getenv scans the environment in order, so another variable before it moves the count, and a file's contents are the host's. So an exact count whose call reads a variable or a path fails the run, naming each read: read it in the benchmark's setup, which no count includes. A count's call follows one the harness does not count, so a read a library makes once a process, as aws-lc's first draw of randomness stats /dev/sysgenid, lands outside it. A harness that never says which call it measures fails an exact count, since its reads would all pass as setup's, and so does another library in LD_PRELOAD, which could replace a function a count runs. A path the host owns, read outside a count, enters the hash by its call, the error it found, and a link's target, never its contents: a host that has /dev/sysgenid where another has none counts in a series of its own, while /proc/cpuinfo's clock speeds, which move run to run, move nothing. Left out are the checkout and what the build wrote, which name where the build is, and what the launch picked, which another host with the same shell would not share: the Nix store, another process's /proc/<pid>, and the cgroup hierarchy std::thread::available_parallelism reads cpu.max under. A link's target in the Nix store or the build is left off its entry, as /etc's links into the store change with each system generation. A path's contents are the host's, so a setup that branches on them counts differently under the same hash, as a variable's value does not. A count other threads ran beside is already sampled, its spread standing for what moves it, so its reads only enter its hash, as std::thread::spawn's first lookup of RUST_MIN_STACK does. CodSpeed's crates tell the preload nothing of their calls, so only the hash covers theirs. Code that walks environ itself, or reaches a file through glibc's own internal calls (getaddrinfo's read of /etc/hosts, realpath's lookups) or a raw syscall, escapes the trace, as it escapes the preload's clock.

Fingerprints

Counts compare only within one environment. Valgrind presents a CPU derived from the host's, and a binary that picks a path by CPU feature, such as glibc's string functions or Rust's runtime detection, counts differently on another; so can another Valgrind, and glibc's tunables, which mask features under the same CPU; so can another preload, whose code runs inside a count and whose seed and clock steer it; so can another simulated cache, and another cycle model moves the estimated cycles; so can the rustflags the host gives the build, such as -C target-cpu=native in ~/.cargo/config.toml. So each run fingerprints its environment: the architecture, every CPUID leaf a probe reads under the same Valgrind, GLIBC_TUNABLES as the benchmarks inherit it, the benchmark processes' mapped libc (by ELF build ID), valgrind --version, the library directory Valgrind adds to the guest's LD_PRELOAD, the preload's bytes, the simulation's options and cycle model, and the rustflags the environment or Cargo's configuration gave the build, as above and not swole's own (nor mbx's remap of a checkout's path to ${workspace}, which builds the bytes swole's does), and where they set a target-cpu or target-feature, what rustc resolves them to (the CPU native names and the target features enabled), since rustc reads the real CPU where Valgrind's CPUID hides some of it, AVX-512 for one (a build given no rustflags has the label of the host alone; a program built outside swole with --build is given none, since swole never sees its flags), hashed into a label such as x86_64-3059cd1d9e65. The measure every count records names it, instructions (x86_64-3059cd1d9e65) and estimated cycles (x86_64-3059cd1d9e65), so counts from two environments never share a Kixel Quest series, and a hardware change starts a new series instead of reading as a regression. swole fingerprint sim prints the host's label for the probe's libc on stdout and its inputs on stderr. A measurement checks that its processes used the probed Valgrind library directory and loaded a single libc build, and prints the fingerprint for that build, which adds the build's rustflags, after counting. Each benchmark's series also carries the hash of what it reads.

A native measure, quick's count or bench's time, follows the host's own CPU, and the counters it reads follow what the host lets swole count. So quick and bench fingerprint the architecture, the CPU's model as /proc/cpuinfo or macOS's machdep.cpu.brand_string names it, how many CPUs the run may use, the build's rustflags as above, and everything the capability probe finds: kernel.perf_event_paranoid, whether swole holds CAP_PERFMON, the PMUs the kernel lists, the core PMU and its counters, and the passes the probe packed them into; on Linux, the mapped libc image (by ELF build ID) loaded by the benchmark processes (refusing runs that mix libc builds or leave a process's libc unverified) and GLIBC_TUNABLES, which pick glibc's string and memory routines; for quick, the preload; and for bench, the cpufreq governor of the core it times on. swole fingerprint quick and swole fingerprint bench run a standalone host probe using the runner's own libc and leasing no core, printing that probe's label on stdout and its inputs on stderr; when a workspace's benchmark targets load a different libc (such as a Nix-packaged runner running benchmarks built in a project dev shell), quick and bench fingerprint the benchmark's mapped libc instead, and bench the governor it found, so look up a measurement series by the fingerprint printed by the run or recorded in --out / --report.

Valgrind 3.27.1 on x86_64 presents one fixed Intel CPU, not the host's: an AMD Ryzen 9 9950X reads GenuineIntel family 6 model 0x3c, Haswell, through it. Hosts that support the same features share a fingerprint when the other inputs match.

The flake pins Valgrind: a nixpkgs bump that moves it fails evaluation until flake.nix's version moves too, since a new Valgrind can count differently and starts new series.

Reuse

sim and quick keep each benchmark's result under ~/.cache/swole/results, one record per benchmark and checkout, and reuse it on the next run, measuring nothing, when everything the result depended on is as it was; the run says reused N of M and, for the rest, how many each reason holds back: no kept result, or the first input that differs, such as executable changed or the variable X changed. A result depends on:

  • swole itself and the mode's fingerprint, Valgrind's launcher, callgrind tool and preload for sim, and how many CPUs it may use;
  • the benchmark's executable, and the contents of every library the dynamic loader lists for it;
  • its launch: arguments, working directory, and the variables swole's harness, Cargo, and CodSpeed set, which what a benchmark reads leaves out of its trace;
  • everything its processes read in setup, traced as that section says, as observed again: each variable's value, a file's contents, a directory's members, a path's metadata (type, permissions, owner, and for a file its size and modification time), a link's target, and a path that was missing.

What swole cannot observe again is never kept: a path opened for writing, a device or other file that is not a regular one, a path the trace could not resolve, a read by a call it does not know, an input written as the run began, a setup that started a process or opened a socket (the preload records fork, posix_spawn, system, popen, and socket, so a child that loads no preload counts too). A benchmark beside which other threads ran, or that read anything in a measured call, is sampled fresh on every run. What the trace misses, a program walking environ itself, a library it dlopens, a process started by vfork, clone, or a raw system call, and what the allocation pass alone reads, the reuse misses too, as sim's exactness does.

A result in quick is the one measured earlier, native counters and all; reuse it when that suffices and pass --no-cache when a fresh count is the point. --no-cache reads and writes no result and never relaxes a check: sim still fails a measured read. bench never reuses a result, and rejects the flag. A record is replaced by the benchmark's next result, so the cache holds at most one per benchmark and checkout; delete ~/.cache/swole/results to clear it.

Compare

swole sim <base> and swole quick <base> count <base> and the working tree in one worktree kept under ~/.cache/swole (or $XDG_CACHE_HOME), each from the directory there that matches where it runs, and print a Markdown table of each benchmark's base, head, and change, the largest changes first, then the benchmarks one side has, then those that held, with the likely cause beside each regression; then one of every other measure that moved: for sim, each simulated event and the estimated cycles, whose change moves a benchmark as its instructions' does, the headline's change naming it (+0.00%, cycles +4.26%) whenever it moved. A sampled (~) value compares by its spread, never as one exact count: between two sampled values, the change says whether their spreads overlap (within spread) or not (beyond spread), and with one side's spread alone, it is marked ~ and gives no verdict. sim then names, for each measure of each benchmark the details print, in their order, the three to five functions whose own cost moved it most, from the Callgrind profiles it already reads (the first run's, marked when the benchmark counts more than once), with a function one side's profile lacks marked, and then the sites behind each allocation change. swole bench <base> builds both sides in the same worktree and times them paired. Both sides' harness targets must resolve swole to the runner's own release, as What it counts requires, so a base from before a swole upgrade fails the run. One directory counts both sides, so a path the build compiles in, such as a panic's location, is the same in each and moves neither count. The worktree sits outside the repository, so no .cargo/config.toml but each side's own configures its build, and is kept so its build stays warm for the next side and the next compare: the head rebuilds only what differs from the base. It first snapshots the working tree as a commit on HEAD, through an index of its own, so the caller's index and stash stay as they were: every tracked file as it is on disk, staged or not, and every untracked one Git does not ignore. An ignored file the caller has, such as a local .env, is on neither side. An ignored one a build leaves in the worktree stays for the next side, but for a Cargo.lock the side's commit does not track, which is removed before each side builds, so each resolves its own dependencies. A submodule with uncommitted changes fails the run, since the snapshot holds only its commit. A clean working tree counts HEAD itself. It refuses two sides whose environment fingerprints differ (the host's); the rustflags a build was given label the series and may differ between sides, since a change to a repository's rustflags is what the comparison measures. A side with no benchmark at all, as a base before the first, counts as none. An absolute --manifest-path in the repository counts the same manifest in the base's worktree, and one outside it is refused, since both sides would count it. A change may add or remove a package or benchmark target, so each side builds only the -p (--package) and --bench selectors its own revision has, from its cargo metadata after its checkout, leaving out each --features package/feature whose package is neither one it builds nor one of their dependencies, and prints each it left out; a --bench is looked for among the packages Cargo builds, every member --workspace does not --exclude, which overrides -p, else those -p selects, else the default ones. A side left with none of the packages, or under --workspace none --exclude leaves, or none of the targets, unless beside --benches or --all-targets, or without the directory compare runs from or the manifest --manifest-path names, counts none, and its benchmarks read as added or removed. A selector neither side has fails, as does one compare cannot resolve by name alone, such as name@1.0 or a glob, and a --features package/feature under Cargo's resolver 1, which also applies it to the current package. Another compare of the same repository waits, on a lock beside the worktree, until this one has counted both sides.

Noise floors

A sim count that is not sampled repeats exactly, and a sampled one carries the spread of its runs, so sim judges a change by those. quick's counts are one native run each, whose instructions an interrupt moves by one or two and whose time, misses, and memory move with the host's load, so swole quick <base> learns how far two counts of the same code differ, for each benchmark and measure of this repository on this host's fingerprint (and, for a benchmark that reads variables of its environment, under the same variables), and judges each change against it instead of a fixed percentage. After it counts the working tree it counts it again: once more for each benchmark whose count is not sampled, and seven more times for those with no floor yet, only those; the recounts always measure fresh. A kept result of the working tree (see Reuse) is judged by its floor as a measured count is, and counts again only when some perf counter event it counted exactly (cycles:u, say) has no floor at its value, and then all eight counts are fresh, since the kept count is of an earlier run's. For each measure it records the most two of those counts differed by and their mean. A floor judges a change only when the mean of its two counts is within twice or half of every count that learned it, which are the working tree's, since the spread of a count of a few instructions says nothing of one in the thousands: a floor learned at 500 judges changes whose mean is 250 to 1,000, and a larger change, or one of a benchmark that counted in another series on each side, has none; a benchmark whose count changed scale relearns a floor on the next run. Each change beside a floor says how it compares, at the mean of the two counts, so it reads the same either way round: +6.66% (1.3× noise) beyond it, (within noise) inside it, or (no noise observed) from a floor of zero, where the counts repeated exactly and any change moves the benchmark. A change within its floor held, whichever of the headline or the details table it is in, a benchmark whose instructions held but whose other perf counter event moved beyond its floor prints its details, and a likely cause is read only from what moved. A measure a run sampled has its own spread and learns no floor.

The floors are one file for each repository (every worktree of a clone shares it, under a lock) and fingerprint under ~/.cache/swole/noise (or $XDG_CACHE_HOME), holding for each measure a few groups of counts, of one scale each, the newest to 28 pairs, and at most the most recently counted benchmarks that fit in 8 MiB, so later runs add to the first rather than replace it, and old code's noise ages out. A floor is the largest spread seen among the groups that judge it, so it shrinks only as old groups age out. Delete the file to learn again. --report records each benchmark's groups as noise, by measure: the absolute spread, the mean_least and mean_most of the counts that had it, and their pairs. bench judges its timing by its own paired intervals, and a sim or bench compare learns no floors.

Quick

swole quick, an agent's local spot-check, counts each benchmark of swole's harness natively, without Valgrind's 20 to 50 times slowdown, with Linux perf counters: its user-space instructions (instructions:u), the headline, and its cycles, branches, branch mispredicts, and L1 data and last-level cache misses, each where the PMU counts it, beside what the process used over the call, as bench reports it. A target of CodSpeed's crates, or a --program, fails the run, as does a host that lets no process count its own instructions, such as a VM without its PMU passed through, a kernel.perf_event_paranoid above 2 without CAP_PERFMON, or GitHub's hosted runners: swole probes the counters before it builds anything, and names why, pointing at sim and bench. --out writes the instructions as instructions:u (x86_64-...) under the native fingerprint, so they share a series only with hosts of the same CPU and counters, never Valgrind's.

Each job runs as a count does, with the preload, which the harness fails a process for not having loaded, and a padded launch, but natively, without address randomization, which the copy loop glibc picks by alignment would follow, and pinned to the CPUs of one core PMU. On a host whose cores are of two kinds, such as Intel's P- and E-cores, each kind has its own PMU, which counts only on its own cores and whose cores report their own cache sizes, from which glibc sizes its copies; so every job runs on the kind with the most cores, and --jobs defaults to how many there are. A job takes one process for each pass of counters the probe packed.

swole opens each job's counters itself, in the job's process just before it execs the target, each counting the thread that runs the benchmark. The harness starts them after the case's setup and then reads each with rdpmc, in user space, through the page the kernel maps for it, and reads them again right after the call, before stopping them, so the system calls that start and stop counting stay out of a count, which holds the call and the reads' own few dozen instructions, the same for every call. A counter that did not run the whole time it was enabled fails the run rather than be scaled up: another user of the host's counters multiplexed it, or the thread left the PMU's cores. Run under Valgrind, the same benchmark counts within those few dozen instructions.

Those counters see the calling thread alone, and the kernel maps no page for a counter a process's threads inherit, so once a pass sees another thread beside a call, as the harness tells, the benchmark counts again with counters every thread inherits: swole opens them with perf's inherit, the harness starts and stops them around each call with the same prctls, and reads each once after the last call with read(), which sums every thread's count, a thread gone by then among them. What the other threads run while a call does is the scheduler's, so like sim, quick counts such a job five times, and records the median of the five, with their least and most, marked sampled (~). Each count also holds the prctls' own few dozen user-space instructions, a fixed cost, the same in every pass. A threaded benchmark counts within a few percent of Valgrind's every-thread count: the fixture's handed, a worker its setup started spinning 100,000 times, counts 406,045 natively against Valgrind's 402,995 on an AMD Ryzen 9 9950X. A benchmark that runs no other thread keeps the calling-thread path. A call much shorter than the timer's tick usually counts the same on each run. Only sim guarantees repeatability for exact counts with matching fingerprints. Each hardware interrupt that lands during a call adds an instruction and a branch to its count, as x86's counters count the return to user space, so a call's count moves with how many interrupts it took, which a longer call takes more often. On one host, an Intel Core Ultra 7 270K Plus at CONFIG_HZ=1000, a 10 ms loop counted 2 to 7 over its 40,000,092 across 15 runs.

Capabilities

quick and bench probe once, before anything builds, what the host lets swole count, and print it: kernel.perf_event_paranoid, whether swole holds CAP_PERFMON (or CAP_SYS_ADMIN), the PMUs under /sys/bus/event_source/devices, the core PMU, how many general-purpose counters it schedules at once, and the counters it found, in passes. The probe opens each counter as a job will, on a thread pinned to the PMU's CPUs, with swole's own privileges, so what it finds is what each job gets; the native fingerprint holds all of it.

  • Tier L2, perf_event_paranoid at most 2: user-space instructions, cycles and instructions a cycle, reference cycles (ref-cycles, cycles at the core's base frequency: Intel's fixed counter, or AMD's from Zen 4 on; bench alone), each ring's three in one group where the PMU fits them, a ratio derived only from counters it counted together, branches and mispredicts, L1 data and instruction, last-level, and data and instruction TLB misses, the top-down breakdown, frontend and backend stall cycles where the PMU counts them, and the kernel's page-faults taken in user space. The thread's time on a CPU, task-clock, is left out: the reads would count in it.
  • Tier L1, perf_event_paranoid at most 1 or CAP_PERFMON: each hardware counter in the kernel as well (:k beside :u), so a syscall's or io_uring's cost shows apart from user space's, page-faults in both, and context-switches and cpu-migrations, which the scheduler counts in the kernel. A count holds none of the kernel's work to start and stop counting, only what the call made it do, and the interrupts that landed meanwhile. Counting starts around each call, or each sample of a benchmark that times itself, whose count holds the reads' few dozen user-space instructions once a sample rather than once a call. quick counts user space alone at any tier.
  • Tier L-1, perf_event_paranoid at most -1 or CAP_PERFMON, on x86_64, and the kernel's syscall and scheduler tracepoints readable under tracefs, outside a nested PID namespace such as a container's, whose thread IDs a wakeup's record does not use: bench traces where each benchmark's threads wait off the CPU, printing that it does or why it cannot.
  • No tier, above 2 without CAP_PERFMON, or a host without a PMU, or one that does not let a process read its counters in user space (cap_user_rdpmc off), or a CPU other than x86_64, or macOS: bench times by wall clock with rusage alone, saying why, and quick fails. A Linux host without a usable PMU still traces off-CPU waits where it grants the L-1 row's privilege and tracefs.

A PMU holds only so many counters at once, and the kernel shares more among them by turns, scaling each up by a guess. swole never lets it: the probe packs the counters into groups that each fit the PMU, by opening them together and checking every one counted the whole time, and a job runs one pass for each group, so no counter shares the PMU with another of the run's. A counter some other user of the PMU still crowded out fails the run.

Privileges

On a host whose perf_event_paranoid stays at its default, grant CAP_PERFMON to swole alone, so its counters reach tier L1 while every benchmark target runs as an ordinary program: swole opens each job's counters before the target execs, which drops the capability, and clears the ambient capabilities a wrapper may have raised, so no target inherits it. Anyone who can run the granted binary can count what swole launches.

sudo setcap cap_perfmon=ep "$(command -v swole)"   # a cargo-installed binary

On NixOS, a wrapper holds the capability, since the store is read-only:

security.wrappers.swole = {
  source = "${swole}/bin/swole";   # swole = github:kixel-ai/swole's packages.<system>.default
  capabilities = "cap_perfmon+ep";
  owner = "root";
  group = "root";
};

cargo swole runs cargo-swole from PATH, which holds no capability: run swole instead. A swole given the capability itself runs its helpers through the cargo-swole installed beside it, since Valgrind refuses an executable that holds capabilities.

A trace of off-CPU waits also reads the IDs of the syscall and scheduler tracepoints it opens from tracefs, which most distributions mount for root alone, and which no capability opens. Grant a group read access when mounting it, by its numeric ID, as the kernel's perf security guide does:

sudo mount -o remount,gid=10,mode=0750 /sys/kernel/tracing   # now, for group 10 (wheel)
# /etc/fstab, at boot:
# tracefs  /sys/kernel/tracing  tracefs  gid=10,mode=0750  0 0

glibc starts a program that holds a capability in its secure mode, which drops LD_LIBRARY_PATH, GLIBC_TUNABLES, and the loader's other variables from its environment, so a granted swole and everything it runs never see them. A count's fingerprint reads the environment swole sees, so it records the tunables as unset.

Bench

swole bench builds the workspace's benchmark targets as a count does, then times each benchmark of swole's harness by wall clock, one at a time, each in its own process, which sets it up once and then runs a sample for each request: as many calls as fill a millisecond of its timed part, found by doubling from one, or of 50 ms of the whole sample, when steps or inputs built between calls take far longer. A benchmark takes samples after a first call that waits out its setup, and its time is their median per call, which the samples a preemption spoiled cannot move. It stops them once the interval around that median is tight, within about 2% either way, checked after 10 samples and each doubling of them, but not before they have taken 100 ms, nor after they have taken 3 s, nor with fewer than ten, and a benchmark whose first ten take a second stops there. It reports no interval: load that slows many samples in a row makes them no independent evidence of it, so one would look far tighter than a repeat run bears out. A target written with CodSpeed's crates fails the run: only a count measures those. The run's processes are neither padded nor shimmed for randomness or time, so their randomness, clock, and addresses are the host's own.

swole bench <base> builds <base> in the worktree a compare keeps, then the working tree, and times each benchmark both have in two processes, the base's and the head's, alive together. It takes their samples in pairs, one of each side, in an order drawn anew for each pair, so load that drifts or recurs on a shared host biases neither side, and load common to both samples of a pair cancels in its ratio. Load that slows one side more than the other, such as a neighbor contending for memory against a memory-bound side, still widens the change's interval, which pairing cannot remove, only balance; the interval takes the ratios as independent, so a run that such load spans for long holds less than it says. Two processes of one build still differ by a few tenths of a percent, by where each lands in memory and on the CPU, which no interval holds: a change that small is one a pair of processes cannot tell. Each side's time is its own samples' median, and the change is the median of each pair's ratio, head over base, with a 95% confidence interval from the order statistics around it, whatever the ratios' distribution, printed as a Markdown table. The pairs stop once that interval leaves out no change or is within about 2% either way, under the same checks, floor, and cap, and the interval is computed at the significance the 5% leaves each of nine looks, so that the interval at whichever look stops them still holds the change with 95% confidence, as one checked after every pair would not. A benchmark only one side has times alone, as added or removed, and a base's benchmarks of CodSpeed's crates time as none, as does a target that lists none, as What it counts says, so a base from before a rewrite to the harness still has its head's times reported. A base builds into its worktree's own target/, in place of any target directory the run names. Each side builds only the Cargo selectors its own revision has, as compare selects them, the working tree's from its files whether committed or not, so a -p or --bench naming a new or removed package or target times its benchmarks as added or removed, and a side left with none of them times none. A selector neither side has fails before either side builds. The base's worktree stays locked until the last benchmark is timed.

Times compare only on one kind of host, so the measure every time records names the native fingerprint, time (x86_64-1a2b3c4d5e6f), in ns a call, so times from two kinds of CPU never share a Kixel Quest series. Pairing can cancel load common to both samples. Timing includes time spent on syscalls, I/O, and contention.

Beside each time, bench reports what the process used over its samples, from getrusage on Linux and macOS: user and system CPU time, minor and major page faults, and voluntary and involuntary context switches, each a call's share, and the process's peak resident memory. Each covers a sample's whole, steps and inputs built between calls included, which the clock leaves out. Where the host has perf counters, bench times and counts on the same core, and counts each side's benchmark with every counter the probe found, one process for each pass, each calling the benchmark as many times as a sample did and counting a deterministic stratified subset of up to 64 of those calls (the same calls in every pass and on both sides), a counter's share of a call. Both the timing and counter processes run under the preload built to count the threads a process starts and nothing else (without 1 MiB stack padding), so their clock and randomness stay the host's while detecting even short-lived workers spawned and joined inside a timed sample or counter pass. Such a benchmark counts every thread, as quick counts a threaded one: its counter passes open counters every thread inherits, when its timed samples saw another thread, or once a pass of the calling thread's counters sees one, and run five times. Counters and same-group ratios use the median of the five with their least and most, marked sampled (~) in the table and as lower and upper in --report. Paired results compare their spreads, and a note under the table names the threaded benchmarks. The top-down percentages use the mean. Each :k count of such a benchmark also holds the kernel's own work to start and stop counting, which no read in user space keeps out: some 10,000 instructions a call on an AMD Ryzen 9 9950X, 18,000 on an Intel E-core, and more with each other thread alive. swole leaves it in rather than subtract a floor, which would take the other threads' kernel work with it. A table after the times prints every measure of each benchmark that moved, beside the base's and its change when paired, with the ratios they derive, as Output says, and --report writes them all.

Functions

When a paired benchmark's time changes, its interval leaving out no change, swole bench <base> compares each side's sampled CPU cycles by function: a threaded benchmark can finish sooner on more cycles, so the functions it names are where its cycles moved, not always its time. On the CPUs its times took, it runs each side once more, in a timed process of its own, over a quarter second of calls, sampling cycles:pp: precise cycles, which the kernel takes with AMD's IBS op or Intel's PEBS, every 250,007 cycles, some 20,000 times a second, each sample at the instruction its cycles end on. It samples each of those CPUs whole and keeps the process's samples alone, since an event each thread inherited would start its period afresh with every thread and miss a worker that lives shorter than one. The harness starts the sampling as its clock starts and stops it as the clock stops, so setup, steps, and inputs built between calls stay out of a profile as they stay out of a time, and neither the times nor the counters share a process with it. swole resolves each sample's instruction pointer against the executable or library mapped there, by the symbols and line tables every mode builds benchmarks with (rustc's -Cdebuginfo=limited -Cstrip=none, after its Cargo profile's own flags, which leave both the code it times and what Cargo tells build scripts as they are), and names the innermost function inlined there that is not Rust's standard library's, whose generic helpers count as the code that called them; a sample in the kernel counts as [kernel]. A table under the measures prints the three to five functions whose sampled self cycles a call (~), on every thread, moved the benchmark's cycles most its way, past three only until they explain the majority of that change, and --report writes every function of each side under the benchmark's functions. A sample the kernel dropped, a stretch it stopped sampling, or a ring buffer that filled fails the run, since the other functions would claim its cycles. A benchmark that times itself names no functions, since its calls may hold work its time leaves out, nor does one whose two sides' clocks bracket unlike windows, such as a sample's calls in one and each call alone in the other.

Sampling needs a PMU that takes precise samples, which a VM's often lacks, and, since it samples whole CPUs, perf_event_paranoid at most 0 or CAP_PERFMON, as Privileges grants; a paired run without them says why and names no functions.

Off-CPU waits

Where the host allows it, bench measures where each side's threads wait off the CPU, a call's share summed over every thread of the process, beside its time and CPUs busy. On the CPUs its times took, it runs each side once more, in a timed process of its own, over a tenth of a second of calls, recording each of the process's context switches and, by the kernel's syscalls:sys_enter_futex and sys_exit_futex tracepoints, its futex calls, and by sched:sched_wakeup, when each of its threads was woken, whatever woke it. As a profile does, it records each of those CPUs whole and keeps the process's records alone, since events every thread inherited would cost each thread the benchmark starts hundreds of microseconds, and the harness starts and stops them with its clock, so setup, steps, and inputs built between calls wait in none of them, and neither the times nor the counters share a process with it. The harness starts the events just after its clock starts and stops them just before the clock stops, and the window opens as its start of the events returns and closes as its stop begins, so it lies within the time, and what other CPUs record before the stop reaches them stays out. Each wait a thread began inside it counts until it ends or the window does, so a worker parked since before the window, waiting for work that never came, counts nothing, nor does a thread's last switch as it exits, which names no thread once Linux reaps it, though a block as it tears down counts:

  • blocked time: off the CPU, waiting on something, as a sleep, I/O, or a futex, until woken;
  • runnable time: off the CPU while runnable, waiting for one, as when the scheduler preempted the thread or has yet to run it once woken, so a loaded CPU's delay counts in no futex or lock wait. A wakeup another CPU than the traced ones records goes unseen, and its wait stays blocked;
  • futex wait time: the blocked time inside a futex call that waits, as a parked worker's or a lock's;
  • lock wait time: the futex wait time at a call that takes a lock. swole resolves each call's site and its caller, through libc's syscall wrapper, against the mapped executable and libraries, as a profile's samples are resolved, and takes a site for a lock where a function inlined there or holding it is std's Mutex::lock_contended or RwLock's read_contended or write_contended, glibc's lll_lock_wait or a pthread_mutex_*lock or pthread_rwlock_*(rd|wr)lock, or the futex operation takes a priority-inheriting lock. A lock of its own futex, as parking_lot's, counts as a futex wait alone, as does a wait on a futex shared between processes that no traced wakeup ended, since another process may have woken it on a CPU swole does not trace.

Each is sampled, between the least and most one sample's calls waited. Samples grow from one call, doubling while one takes under 10 ms, to as many calls as a timed sample, and swole reads the rings while a sample runs, each time one holds 64 KiB. A sample whose events lost a record, as each counts, which a burst of other processes' records on its CPUs can cause as well as its own, counts nothing, and no later sample takes as many calls; a side left with no sample fails the run. A trace counts its losses from Linux 6.0 on. A benchmark that times itself has none, since its calls may hold waits its time leaves out. A sample whose records miss one of its clock's windows, as when the benchmark moves its thread off the CPUs swole traces, fails the run. A trace needs the host's tier L-1, as Capabilities says, and its tracepoints' IDs from tracefs, as Privileges grants; a run without them says why and has no waits.

Cores

On Linux, bench leases one physical core once its builds are done and times every benchmark process that runs no other thread on that core's first hardware thread swole may run on, so a sample never migrates and a pair's two sides run on one core. The lease is an advisory lock on a file in /dev/shm/swole, shared by every user, which the run releases and the kernel drops however the run ends: no other swole bench uses any hardware thread of the core meanwhile, so concurrent runs take disjoint cores and never contend through an SMT sibling. A run takes the last free core, leaving the first, where the kernel does most of its own work, for last, and when other runs hold them all, waits until any one frees. On a hybrid Intel host it takes a performance core, counted by the cpu_core PMU, while quick counts on the PMU of the most CPUs. Each benchmark starts on the run's core and every other core no other run leases, so one that checks at setup that it may use the host's CPUs can, and narrows to the one CPU, in a new process, once its first call runs no other thread. Where other runs lease every other core and the run's own has no SMT sibling, that spread would be one CPU, which a benchmark sized to the host fails at setup, so the run waits for another core to free instead; a host swole may use one CPU of gets it. Runs that all hold a core while they wait for a second would wait forever, so the one on the last core fails, naming why, and frees its core for the rest. One whose first call runs another thread would have its threads serialized on one CPU, so it keeps those cores until it is counted, and the run says so; its counter passes run there too, and count every thread, as above. One whose threads start only later is timed and counted again on them.

The lease keeps other swole bench runs off the core, not the host's other processes, which the run says unless the kernel excludes the CPU from scheduler load balancing (isolcpus, listed in /sys/devices/system/cpu/isolated); even then a task pinned there may still run on it.

Where swole may write the core's cpufreq policy, and the policy sets no CPU outside the core, a run switches the core to the performance governor, recording what it changed first in a journal beside the lease that only its user may write, and restores the governor and energy preference when it exits or a SIGINT, SIGTERM, or SIGHUP ends it; the next run of that user to lease the core restores what a run killed outright left. Elsewhere it times under the host's governor and says why. Either way the governor it times under enters the fingerprint, so times under two governors never share a series. sysfs attributes take a group and mode, so a host grants its benchmarking group the governors and energy preferences at boot:

# /etc/tmpfiles.d/swole-cpufreq.conf
z /sys/devices/system/cpu/cpufreq/policy*/scaling_governor               0664 root wheel -
z /sys/devices/system/cpu/cpufreq/policy*/energy_performance_preference  0664 root wheel -

Allocations

Every mode counts each benchmark of swole's harness's heap allocations: alloc_count, the allocations a call makes; alloc_bytes, the bytes they ask for; peak_live_bytes, the most bytes the call's own allocations hold at once, which a free of a block allocated before the call never lowers; and retained_bytes, the heap the call still holds when it returns, its returned value included: the bytes it allocated less every byte it freed, blocks from its setup included, so a setup structure the call regrows counts only its growth, and a call that frees more than it keeps, such as one that drops its input, reads negative. A benchmark that defers its frees, as an epoch-based collector does, flushes them inside the call for them to count. They count in a pass of their own, one process that sets the benchmark up and calls it twice, as a count does, under an interposer of glibc's allocator (malloc, calloc, realloc, reallocarray, free, posix_memalign, aligned_alloc, memalign, valloc, pvalloc), which the harness has count only between the same requests that bracket a count, so neither setup, the first call, nor the call's output's drop counts: a structure kept across calls that the first call grows to fit reads no growth in the second. The interposer tracks every block it hands out from the start of the process, so a free during the counted call knows the size of a block from before it, though not of one the loader allocated before the interposer found the allocator. A realloc counts as an allocation of its new size and a free of the old block. No other pass loads the interposer, so its hooks' instructions are in no count, cycle, or time. Beside quick and sim, the pass runs under the preload's randomness and clock and a padded launch, as their counts do; beside bench, under the host's, as its times do. On macOS, bench inserts an interposer of libSystem's allocator with DYLD_INSERT_LIBRARIES; elsewhere but x86_64 Linux, a run has no allocation counts, and says so.

A call no other thread ran beside, as the harness watches, counts exactly, the same on every run, but for one whose allocations follow an input the host decides. One beside which another thread ran, even one that never allocates, is sampled: the interposer counts every thread's allocations and cannot tell whose each was, so the pass runs five times and each measure is the median of the five, with their least and most, marked ~ in the tables. A compare's change of a sampled measure says whether it is within the spread of the two sides' samples or beyond it, and with one side's spread alone, nothing more than its ~. A change of retained_bytes is its signed difference in bytes, never a percentage, which from a base at or below zero would read backwards.

A benchmark whose global allocator never reaches glibc's malloc, as a #[global_allocator] that maps memory of its own or a static allocator that defines malloc in the executable does, has no allocation counts rather than counts of none: the harness first allocates through the global allocator under the interposer and, when it sees nothing, says so, and swole names the benchmark on stderr. A static executable, which loads no interposer, fails the pass.

--out holds the four as alloc_count (<fingerprint>+<interposer>) and the rest, the mode's fingerprint followed by a hash of the interposer that counted them, since a change to how it counts can move them, and the hash of what the benchmark reads when it reads any, beside the headline for each benchmark that has them, a sampled one's with its lower_value and upper_value. --report marks each as the allocation pass's ("pass":"allocation") and says whether it is sampled, and adds alloc_churn, the bytes a call allocated for each byte of its peak.

Sites

sim also names where each benchmark's allocations come from, from the Callgrind profiles it already reads: Callgrind names each call into glibc's allocating functions by up to 40 callers on its stack (--separate-callers, which moves no count, so no fingerprint), and an allocation's site is the first of them in the workspace's own crates, else the first outside the allocator, glibc, and Rust's standard library, whose generic helpers count as the code that called them, with the function it called toward the allocator: `a::fill` → `<alloc::raw_vec::RawVec<u64>>::grow_one`. A #[global_allocator]'s own code, under Rust's allocation shim, counts as the allocator's. A call one allocating function makes to another, as realloc of no block makes to malloc, is the outer call's allocation, so the sites partition the allocations as the allocation pass counts them. For a call no other thread ran beside, a benchmark whose sites do not add up to its alloc_count, as one whose allocation failed, which Callgrind sees as a call and the pass does not count, names no sites, and swole says so on stderr; its counts stand. A sampled benchmark's sites are its first run's. --report writes every site of each side under the benchmark's alloc_sites, the most allocations first (function, calling, allocations), and a <base> compare prints, below the functions behind each change, the three to five sites whose allocations moved a benchmark's most its way, as it picks functions. Sites count calls, not bytes, since Callgrind sees no call's arguments.

Recorded counts

A benchmark's own counts, such as worker turns, come beside swole's measures in every mode, unit count, and divide by a declared throughput as other counts do, such as turns/item. They enter no fingerprint: they are the benchmark's output, as its instructions are.

  • sim reads them from the Callgrind run. A call alone repeats exactly under the preload, so its counts are exact; one beside which another thread ran counts five times, each the median of the five with their least and most (~), as its instructions are.
  • quick reads them from its counting call, in each pass's process: exact when the passes agree, else their median with their least and most (~).
  • bench reads each timed sample's total over its calls, a call's share each, and reports each side's median with its interval, never as exact, since native counts can move. A paired run pairs them, and their shares of a byte or an item, as it pairs times: the change is the median of each pair's head over base with its interval, or, where a base sample counted none, the change of the medians, marked within or beyond their intervals.

The harness prints only the counters a call or sample added to, so a counter added to only on some path counts as zero in each run or sample of that side that lacks it. --out holds each as <counter> (<fingerprint>) beside the headline, with the environment's hash where the headline's has it, unit count, a sampled one's or bench's with its lower_value and upper_value.

Diagnostics

Beside each measure a run takes, swole derives the ratios that say why a benchmark runs as it does, each where the run took what it divides, into the details table and --report:

  • misses per thousand instructions (MPKI): natively the L1 data and instruction, last-level, and data and instruction TLB misses and the branch mispredicts, in each ring (L1d MPKI:u), and under sim the simulated L1 instruction and data, last-level, and branch misses (LL MPKI);
  • the branch miss rate, mispredicts over branches;
  • the kernel's share of the instructions, where tier L1 counts both rings, and under bench of the CPU time, from rusage;
  • under bench, where one clock times each whole sample, CPUs busy: the process's average CPU occupancy, the CPU time it used, user and system, over its samples' wall clock, as the harness measures both, sampled between the least and most one sample was, since the scheduler moves it. Under one, the process was off the CPU, as on a lock or I/O, or when the host ran something else; over one, it ran threads in parallel, any of the process's beside the benchmark's own included;
  • cycles/ref-cycles in each ring, counted in one group over one window, which falls as the core throttles and rises with turbo; or, where the PMU counts no reference cycles, under bench, an estimated clock:u in GHz, the counted cycles over the timed process's user time, which also holds what a sample ran between calls. The estimate requires the user-time range to stay above zero.
  • the top-down breakdown under bench, each a percentage of the dispatch slots: the first level's retiring, bad speculation, frontend bound, and backend bound, and the second level's split of each, heavy and light operations, branch mispredicts and machine clears, fetch latency and bandwidth, and memory and core bound. Intel's performance cores count it as slots and its top-down metrics, which rdpmc would read as fractions, so the harness reads that pass with read() alone, marked (read) in the probe's passes. Intel's shares divide the first-level events by their sum, as perf does, so rounding the performance cores' hardware fractions cannot make the shares exceed the slots. On AMD Zen 4 and 5, swole counts the events perf's own metrics divide (de_no_dispatch_per_slot.*, ex_ret_ops, and the rest, by perf's names). It uses six or eight slots a cycle and includes the SMT sibling's share where the PMU has a counter to spare. If the counted categories disagree with the budget at the window edges, swole divides by the greater of the slots and the accounted total. The breakdown counts user space alone and splits each AMD first-level share using a pair counted together. On AMD the fetch latency estimate scales with the same slot budget as frontend bound. Top-down percentages average five rounds, marked sampled (~) with the least and most observed. Each round divides its own slots, and single-threaded benchmarks repeat only the passes that feed the breakdown. Counters and same-group ratios from those passes also show their observed range.

A ratio of a sampled measure is sampled, its spread the widest its inputs' allow. A percentage's change shows in points (pp).

A paired bench's regression, a slowdown whose whole interval lies above no change, and a compare's, a headline count, or sim's estimated cycles, grown past its spread, names its likely cause in a column beside it, from the first two of these its measures show, each citing the measure on both sides: throttled (cycles/ref-cycles:u fell 2%; never the estimated clock alone), off-CPU (CPUs busy lost 0.1 and ended under 0.9), named, where a trace split it, for the narrowest wait that gained half or more of the off-CPU time a call gained, lock contention, futex wait, blocked, or runnable, citing it beside CPUs busy, more instructions (1% more), memory-bound (the last-level, L1 data, or data TLB MPKI grew by a quarter and 0.1, or the breakdown's memory bound gained 3 points), else backend-bound (its backend bound did), branch mispredicts (its miss rate, MPKI, or share), else bad speculation, frontend-bound, kernel (its share gained 5 points), and for a time that moved 1 to 3% with its instructions, branches, and some MPKI counted on both sides the same, and the breakdown's frontend bound, where it counts one, grown past its spread, likely code alignment: the same code at other addresses, as an unrelated change can shift it. A sampled measure counts only past its spread, a side counted once past its one value.

Scaling

A benchmark whose #[bench(args = [..])] are positive numbers, such as [100, 1_000, 10_000], or byte sizes such as 32B and 16KB, is a sweep when it has at least three distinct sizes and the largest is ten times the least. Every numeric argument reads as a size, so a sweep of thread counts or seeds gets a class too, and means little. After the details, swole fits each sweep's instructions, estimated cycles (sim), allocations (alloc_count), and under bench wall-clock time to its size n as a constant beside O(1), O(log n), O(n), O(n log n), or O(n²) growth, by least squares on relative error, and prints the class. BIC chooses the class, and the simplest one within 2 of the best wins, so noise does not make a curve steeper. A count that varies between runs, and every wall-clock time, is sampled (~), and fits against 5% of noise rather than 1%. A measure that is zero at any size has no class, since no ratio of it is defined, and neither has a time a benchmark returns itself.

With <base>, only the sweeps whose class changed print, as O(n) → O(n²) marked regressed or improved, so a change that left every size within its noise still shows a loop that went from linear to quadratic; a note counts the measures that held and the sweeps whose sizes no longer overlap enough to compare. Both sides fit the sizes both ran, against the noise of the noisier, so neither a changed list of args nor a side that turned exact or sampled moves a class by itself. A class changes only when no one growth curve, with a fixed cost of its own on each side, explains both sides within the noise, so a fixed setup cost that grew or shrank is no change. A count that drops by one constant across a step in sizes, which no one curve reproduces, still shows as a change. The class is a fit of a few sizes, not a proof: sizes under a hundred, or a sweep of one order of magnitude, can fit a neighbor of the true class.

Inspect

swole inspect <benchmark> [<base>] [-- <cargo bench args>] says where one benchmark's simulated cost falls inside its hot functions, so a missed vectorization, an inlining change, a bounds check, or bloated code reads off one command. It builds the benchmarks with symbols and line tables, like bench, and runs the one named, a whole name or any part that names only one, under the sim Valgrind with Callgrind dumping every source line and instruction (--dump-line=yes --dump-instr=yes); sim itself leaves both off, so bulk counts stay fast. It is Linux's, like sim, and disassembles with objdump, which the flake's wrapper and dev shell carry. It prints:

  • the benchmark's estimated cycles and instructions, and the hottest functions by self cost, each with the byte size of its symbol in the benchmark's executable, and that executable's whole .text;
  • the source lines whose cost is greatest, each with its text;
  • the disassembly of the three hottest functions of the benchmark's own executable, each executed instruction with the instructions and cycles it cost and its source line, the hottest 120 when more ran.

With <base>, a commit, it profiles <base> in compare's worktree too, and instead prints each count, symbol size, and .text as base → head, the source lines whose cost moved most, and for each hot function both sides have, a diff of its disassembly: each instruction only one side has, with its cycles and source line. Instructions compare by their text, less absolute addresses and displacements from the instruction pointer, which a function's moving shifts, so only a changed instruction reads as changed; source lines compare by file and number, so a line the change moved reads as changed. A run counts once, so a benchmark that ran another thread beside it says its costs can move.

Every --report of sim, quick, and bench also records text_bytes, the size of the .text of the executable each benchmark ran in, by side, read after the run, so a regression in code size shows without inspecting.

Bisect

swole bisect <good> <bad> finds the first commit that regressed a benchmark, in one command. It counts <good> and <bad> with every benchmark (or those --benchmarks lists), picks the headline that rose most past the spreads of both sides, a benchmark's instructions or, under sim, its estimated cycles, and halves the commits between them on <bad>'s first-parent history, counting only that benchmark at each midpoint. A midpoint within a quarter of the gap between the two sides' samples of either takes that side; one in the middle half, or whose samples reach into the other side's, fails the run, since a regression spread over several commits, or lost in noise, has no first one. The search assumes one good-to-bad transition: a regression, its revert, and its reintroduction can name the reintroduction. It prints the first bad commit and a table of every commit it counted, a sampled reading with its range.

Each step checks its commit out in compare's cached worktree under ~/.cache/swole, so the caller's working tree, index, and stash are untouched and the build products of one step serve the next: a step recompiles what its commit changed, not the workspace. It counts as sim, exact across hosts that share a fingerprint, unless --mode quick asks for the faster native count, which takes each reading once; quick therefore counts the culprit and its predecessor a second time, shows the range of both counts, and fails unless both count as they did. bench is refused, since a wall clock is too noisy to halve a span by.

It fails, naming the commit, when a midpoint does not build, lacks the benchmark, or counts under another host's fingerprint (the rustflags a commit gives its build do not count, as in compare), and when <good> and <bad> count under two, <good> is not on <bad>'s first-parent history, or <bad> counts no more than <good>. It reads --benchmarks as every command does, a file of names, and takes neither --out, --report, nor --allow-missing.

Output

stdout keeps a large suite's results short: each headline table prints every benchmark, sorted by its change, and the details table after it prints every other measure only of the benchmarks that moved (or one side has), and of each, only the rows that moved, with a note of what it left out; a suite of at most ten benchmarks prints every one, and --all-details every row of every one. A run without a base moves nothing, so a suite of more than ten prints no details, and says so. --report holds them all. A change from an exact zero shows the absolute change, as +3, rather than a percentage of none.

--out writes each benchmark's headline measures, available heap allocation measures, and recorded counts. It fails if the file would exceed the 1 MiB Kixel Quest reads. sim --out and quick --out write one sample of the run's commit: sim's instructions and estimated cycles, quick's instructions:u (...), and for a benchmark counted several times, each measure's median with the least and most of its samples:

{"samples":[{"metrics":{"benches/varint.rs::varint::encode[1]":{"estimated cycles (x86_64-3059cd1d9e65)":{"value":15467},"instructions (x86_64-3059cd1d9e65)":{"value":12345}},
                        "benches/pool.rs::spawn":{"estimated cycles (x86_64-3059cd1d9e65)":{"value":512330,"lower_value":509914,"upper_value":515102},
                                                  "instructions (x86_64-3059cd1d9e65)":{"value":402614,"lower_value":402137,"upper_value":403005}}}}],
 "units":{"estimated cycles (x86_64-3059cd1d9e65)":"cycles","instructions (x86_64-3059cd1d9e65)":"instructions"}}

bench --out writes the working tree's times as the run's own sample, and with a base, the base's as a sample naming its commit:

{"samples":[{"commit":"<the base's full commit ID>","metrics":{"benches/varint.rs::encode[300]":{"time (x86_64-1a2b3c4d5e6f)":{"value":20.3}}}},
            {"metrics":{"benches/varint.rs::encode[300]":{"time (x86_64-1a2b3c4d5e6f)":{"value":19.2}}}}],
 "units":{"time (x86_64-1a2b3c4d5e6f)":"ns"}}

--report <file> writes every measure of every benchmark, by side, as JSON: its schema_version, the mode, the fingerprint and its inputs, the base's commit when there is one, and for each benchmark, each side's measures by name, each a value and a unit (a call's share, for bench), and for one counted several times, the lower and upper of its samples, for sim every simulated event and the estimated cycles, whether another thread ran beside it, the text_bytes of the executable it ran in by side, for quick compares each measure's learned noise floors as noise, and for a paired bench, the change and its interval. A benchmark that declares its throughput has each count and its allocations' per byte or item beside it, such as estimated cycles/byte or instructions:u/byte, and under bench a throughput in bytes/s or items/s, except for a benchmark that times itself, whose returned time is not wall clock:

{"schema_version":1,"mode":"bench","fingerprint":"x86_64-1a2b3c4d5e6f","host":["arch: x86_64","..."],"base":"<the base's full commit ID>",
 "benchmarks":{"benches/varint.rs::encode[300]":{
   "base":{"time":{"value":20.3,"unit":"ns"},"instructions:u":{"value":81.0,"unit":"events"},"user time":{"value":20.1,"unit":"ns"}},
   "head":{"time":{"value":19.2,"unit":"ns"},"instructions:u":{"value":77.0,"unit":"events"},"user time":{"value":19.0,"unit":"ns"}},
   "change":{"value":0.9458,"lower":0.9412,"upper":0.9501,"unit":"head/base"}}}}

schema_version is 1, and moves only when a field it holds changes meaning or goes away: a reader that knows its version reads every field it knows the same way, and ignores one it does not, which a new measure or field may add without moving it.

A benchmark's name is the one its hooks dump, which for CodSpeed's crates is the file relative to the repository, then its group, function, and parameter: the same name CodSpeed gave it, so only the measure differs. The harness names its own the same way, by file, module, function, and argument.

About

Rust benchmarks counted under stock Valgrind and timed in pairs

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages