Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 38 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,13 @@ It may additionally define:
One benchmark at one size, in one process, is:

```sh
R --no-echo --vanilla -f benchmarks/harness.R --args <benchmark>.R <warmups+iterations> <size>
R --slave --vanilla -f benchmarks/harness.R --args <benchmark>.R <warmups+iterations> <size>
```

`--slave` is R's pre-4.0 name for `--no-echo`. R 4.x still accepts it without a
word, and it is the only spelling R 3.x knows, so one command line runs every R
from 3.0 on. The harnesses themselves stick to base R that 3.0 already had.

The harness sources `RBENCH_PROFILE` if set, then `setwd()`s to the
**benchmark's own directory** — which is what lets a benchmark reach its `data/`
cache and its helpers by relative path, and `shootout` reach `../fasta/` — then
Expand Down Expand Up @@ -96,7 +100,7 @@ one benchmark:

```sh
cd benchmarks
R --no-echo --vanilla -f harness.R --args areWeFast/mandelbrot.R 3
R --slave --vanilla -f harness.R --args areWeFast/mandelbrot.R 3
```

That prints a `====== ... completed in <t> ms ... ======` line per iteration and
Expand All @@ -111,7 +115,7 @@ yourself:
cd benchmarks
env OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 \
VECLIB_MAXIMUM_THREADS=1 R_LIBS=" " R_LIBS_USER=" " R_LIBS_SITE=" " \
R --no-echo --vanilla -f harness.R --args riposte/kmeans.R 3
R --slave --vanilla -f harness.R --args riposte/kmeans.R 3
```

The single space in `R_LIBS*` is deliberate and not the same as `""`: R
Expand Down Expand Up @@ -227,6 +231,24 @@ a leaf-only recording). Which one you pick changes the answer, not just the
cost; `dwarf` is the default because it is the only mode that carries inlined
callees.

Each recording lands in `<dir>/<suite>/<benchmark>/<variant>/<run>/`: `perf.data`,
the `perf script` frame table `perf-frames.csv`, and the run's `stdout` with its
`MARK` lines. [`profile/categorize.R`](profile/categorize.R) turns a `--dir` tree
into the share of `execute()` each category of R's runtime takes (interpreter,
call, dispatch, lookup, primitives, mem-alloc, mem-duplicate, mem-gc,
native-ffi, native-blas, other, and what stayed unattributed), plus the
largest reasons a sample stayed unattributed:

```sh
Rscript profile/categorize.R --causes output/causes.csv output/categories.csv output/perf
```

The classification is [`profile/perf-rules.R`](profile/perf-rules.R), taken
unchanged from the paper artifact it was written for (see
[`profile/ORIGIN.md`](profile/ORIGIN.md)); `categorize.R` only applies it. It
runs on the analysis machine, not on the R being measured, and needs R >= 4.1
with dplyr, tidyr, readr, stringr and tibble.

## Adding your own benchmarks

Suites are **declared, not discovered**: `SUITES` in `rbench.py` is the corpus,
Expand Down Expand Up @@ -281,19 +303,24 @@ same framing — and land in the same report.
## Building your own driver

`rbench.py` is a module as well as a script. Import `base_app()` and override
only what differs; `bench`'s builder replaces rather than accumulates, so
everything you do not name stays identical to the plain run:
only what differs; everything you do not name stays identical to the plain
run:

```python
import rbench as rb

@dataclass(frozen=True)
class Params(rb.Params):
class Params(rb.Params): # no @dataclass: bench makes it one, frozen and keyword-only
my_flag: int = 5

app = rb.base_app(Params).with_env(lambda ctx: {**rb.bench_env(ctx.params), ...})
```

`with_env` merges into the sealed environment; replacing a setting `base_app`
already made (the command, the metrics, the controller, ...) takes
`override=True`, or `bench` warns that it is overriding it. Run the app with
`rb.main(app)` rather than `app.main()` to keep the `--show FILE` spelling (`bench`
itself now takes `show FILE` as a subcommand).

`rbench_perf.py` is the worked example: it changes the command, the metrics and
the output tree, and inherits the corpus, the sizes, the shuffle seed and the
environment.
Expand Down Expand Up @@ -343,7 +370,9 @@ The five BSD-3-Clause suites were ported from the **R Benchmark Suite (RB)**,
`# Upstream:` comment pointing back to it. RB had itself repackaged several from
their own upstreams; both links are in each `ORIGIN.md`.

The harnesses (`harness*.R`), `marker.c` and the drivers are this repository's
own work, under the MIT license — see [`LICENSE`](LICENSE). The vendored suites
The harnesses (`harness*.R`), `marker.c`, the drivers and `profile/` are this
repository's own work, under the MIT license — see [`LICENSE`](LICENSE).
`profile/perf-rules.R` comes from the VMIL26 paper artifact; see
[`profile/ORIGIN.md`](profile/ORIGIN.md). The vendored suites
keep the licenses above; those are the upstreams' terms and are not ours to
change.
2 changes: 1 addition & 1 deletion benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ only says what the loose files beside the suites are for.
The harness. Runs one benchmark in one R process:

```sh
R --no-echo --vanilla -f harness.R --args <benchmark.R> <iterations> [<size>]
R --slave --vanilla -f harness.R --args <benchmark.R> <iterations> [<size>]
```

Sources `RBENCH_PROFILE` if set, `setwd()`s to the benchmark's own directory,
Expand Down
4 changes: 3 additions & 1 deletion benchmarks/harness.R
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,9 @@ for (i in seq_len(iters)) {
# `gc.time()` is quantized to 1 ms and only starts accumulating on its first
# call, so it would report this first forced GC as 0.
forced <- Sys.time()
gc(full = TRUE)
# `gc()` and not `gc(full = TRUE)`: `full` only exists from R 3.5.0, where it
# defaults to TRUE, and before that every `gc()` collected all generations.
gc()
forced <- as.numeric(difftime(Sys.time(), forced, units = "secs"))

g0 <- gc.time()
Expand Down
4 changes: 3 additions & 1 deletion benchmarks/harness_instrument.R
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ if (exists("setup") && is.function(setup)) {

# A phase of its own so that neither its cost nor `setup`'s garbage lands in
# `execute`.
# `gc()` and not `gc(full = TRUE)`: `full` only exists from R 3.5.0, where it
# defaults to TRUE, and before that every `gc()` collected all generations.
t0 <- now()
invisible(gc(full = TRUE))
invisible(gc())
t1 <- now()
mark("gc", t0, t1)

Expand Down
24 changes: 24 additions & 0 deletions profile/ORIGIN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# profile/

## `perf-rules.R`

Copied **unchanged** from the artifact of the VMIL26 paper *What do R
benchmarks measure?*: `analysis/perf-rules.R` at commit `8b42516` of
`fikovnik/VMIL26` (the file was last changed in `d69f08d`, 2026-08-29, by
Filip Křikava).

It is the frame classification behind the paper's category profiles: the
rules that map a `perf` stack frame to a category of R's runtime, and the walk
that charges each sample to its innermost classified frame. Its own header says
the rules and the walk only mean anything together, so it is kept whole and
byte-identical, and not reimplemented elsewhere. A change to it belongs upstream
first, then here as a fresh copy.

Licence: the VMIL26 repository is private. Its author, Filip Křikava, agreed
to publishing this file here under this repository's MIT licence.

## `categorize.R`

This repository's own (MIT). It applies `perf-rules.R` to the recordings
`rbench_perf.py` writes, the same way VMIL26's `analysis/categories.Rmd` does,
and writes the per-recording category shares as a tidy CSV.
228 changes: 228 additions & 0 deletions profile/categorize.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
#!/usr/bin/env Rscript
#
# Category shares of `execute()` from `rbench_perf.py` recordings.
#
# Usage:
# Rscript profile/categorize.R [--causes FILE] [--top N] OUT.csv DIR...
#
# Each DIR is the `--dir` root of an `rbench_perf.py` run, searched recursively
# for `perf-frames.csv`. A recording is the directory holding one, laid out as
#
# <dir>/<suite>/<benchmark>/<variant>/<run>/{perf-frames.csv,stdout,...}
#
# where `stdout` carries the `MARK` lines `harness_instrument.R` printed. The
# recording's key is read off that path below DIR (a benchmark may itself be
# nested, `shootout/nbody/nbody_naive`), so DIR has to be the root, not a
# directory inside it.
#
# For every recording this applies `perf-rules.R` -- the frame classification
# and the walk from the VMIL26 paper artifact, kept here unchanged -- exactly as
# its `categories.Rmd` does: frames are tagged with the harness phase their
# sample fell in, classified, each sample is charged to its innermost classified
# frame, and only samples inside the `execute` phase are counted.
#
# OUT.csv, one row per (recording, category), every category present (zero when
# none of its samples were seen) plus `unattributed`:
#
# suite, benchmark, variant, run which recording
# category a category of CATEGORIES, or `unattributed`
# samples execute() samples charged to it
# kernel_samples all execute() samples of the recording
# share samples / kernel_samples; the categories
# and `unattributed` sum to 1
# share_classified samples / the classified kernel samples,
# i.e. VMIL26's per-run `pct` / 100; NA for
# `unattributed`
#
# --causes FILE writes, per recording, the N (default 10) largest reasons an
# execute() sample carries no category, from `unclassified_causes()`:
#
# suite, benchmark, variant, run, cause, leaf_sym, leaf_dso, samples, share
#
# with `share` again of all the recording's execute() samples.
#
# Runs on the analysis host, not on the R being measured: it needs R >= 4.1 and
# dplyr, tidyr, readr, stringr and tibble.

suppressPackageStartupMessages({
library(dplyr)
library(tidyr)
library(readr)
library(stringr)
library(tibble)
})

# The categories `perf-rules.R` produces, in the order the paper reports them
# (VMIL26 `analysis/setup.R`, `CAT_GROUPS`). `other` is the interpreter's own
# outer frames (`main`, `Rf_mainloop`, ...) when nothing deeper matched.
CATEGORIES <- c(
"interpreter", "call", "dispatch", "lookup",
"primitives",
"mem-alloc", "mem-duplicate", "mem-gc",
"native-ffi", "native-blas",
"other"
)
UNATTRIBUTED <- "unattributed"

here <- local({
f <- sub("^--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE))
if (length(f) == 1L) dirname(normalizePath(f)) else "profile"
})
source(file.path(here, "perf-rules.R")) # `rules` and the walk, unchanged

# As categories.Rmd checks it: a rule whose category is not reported would
# silently never show up.
stopifnot(all(rules$category %in% CATEGORIES))

usage <- function() {
stop("usage: categorize.R [--causes FILE] [--top N] OUT.csv DIR...",
call. = FALSE)
}

parse_args <- function(args) {
opts <- list(causes = NULL, top = 10L, out = NULL, dirs = character())
i <- 1L
while (i <= length(args)) {
a <- args[[i]]
if (a %in% c("--causes", "--top")) {
if (i == length(args)) usage()
v <- args[[i + 1L]]
if (a == "--causes") opts$causes <- v else opts$top <- as.integer(v)
i <- i + 2L
} else if (startsWith(a, "--")) {
usage()
} else if (is.null(opts$out)) {
opts$out <- a
i <- i + 1L
} else {
opts$dirs <- c(opts$dirs, a)
i <- i + 1L
}
}
if (is.null(opts$out) || !length(opts$dirs) || is.na(opts$top)) usage()
opts
}

#' Every recording under `dirs`, keyed by its path below the root it was found
#' in: `<suite>/<benchmark...>/<variant>/<run>`.
find_recordings <- function(dirs) {
bind_rows(lapply(dirs, function(root) {
root <- normalizePath(root, mustWork = TRUE)
fs <- list.files(root, "^perf-frames\\.csv$", recursive = TRUE,
full.names = TRUE)
rec <- dirname(fs)
parts <- str_split(str_remove(rec, fixed(paste0(root, "/"))), "/")
ok <- lengths(parts) >= 4L
if (any(!ok)) {
warning("not <suite>/<benchmark>/<variant>/<run>, skipped: ",
paste(rec[!ok], collapse = ", "), call. = FALSE)
}
parts <- parts[ok]
tibble(
suite = vapply(parts, `[[`, "", 1L),
benchmark = vapply(parts, function(p) paste(p[2:(length(p) - 2L)],
collapse = "/"), ""),
variant = vapply(parts, function(p) p[[length(p) - 1L]], ""),
run = vapply(parts, function(p) p[[length(p)]], ""),
frames = fs[ok],
stdout = file.path(rec[ok], "stdout")
)
})) |>
arrange(suite, benchmark, variant, run)
}

#' The execute() samples of one recording, one row each, with its category.
kernel_of <- function(rec) {
marks <- read_perf_marks(rec$stdout)
if (!any(marks$region == "execute")) {
warning(rec$frames, ": no `MARK execute` line in ", rec$stdout,
"; recording skipped", call. = FALSE)
return(NULL)
}
frames <- read_perf_frames(rec$frames)
if (!nrow(frames)) {
warning(rec$frames, ": no frames; recording skipped", call. = FALSE)
return(NULL)
}
frames <- frames |>
add_marked_region(marks) |>
classify_frames(rules)
kernel <- sample_regions(frames) |>
filter(!is.na(region), region == "execute")
if (!nrow(kernel)) {
warning(rec$frames, ": no samples inside execute(); recording skipped",
call. = FALSE)
return(NULL)
}
kernel
}

categorize <- function(rec, kernel) {
key <- select(rec, suite, benchmark, variant, run)
counts <- kernel |>
mutate(category = coalesce(category, UNATTRIBUTED)) |>
count(category, name = "samples")
out <- tibble(category = c(CATEGORIES, UNATTRIBUTED)) |>
left_join(counts, by = "category") |>
mutate(
samples = coalesce(samples, 0L),
kernel_samples = nrow(kernel),
share = samples / kernel_samples,
classified = sum(samples[category != UNATTRIBUTED]),
share_classified = if_else(category == UNATTRIBUTED, NA_real_,
samples / classified)
) |>
select(-classified)
bind_cols(key[rep(1L, nrow(out)), ], out)
}

causes_of <- function(rec, kernel, top) {
key <- select(rec, suite, benchmark, variant, run)
causes <- unclassified_causes(kernel) |>
arrange(desc(samples), cause, leaf_sym) |>
slice_head(n = top) |>
mutate(share = samples / nrow(kernel))
if (!nrow(causes)) return(NULL)
bind_cols(key[rep(1L, nrow(causes)), ], causes)
}

main <- function(args) {
opts <- parse_args(args)
recs <- find_recordings(opts$dirs)
if (!nrow(recs)) stop("no perf-frames.csv under ", paste(opts$dirs, collapse = ", "),
call. = FALSE)

shares <- list()
causes <- list()
for (i in seq_len(nrow(recs))) {
rec <- recs[i, ]
kernel <- kernel_of(rec)
if (is.null(kernel)) next
shares[[length(shares) + 1L]] <- categorize(rec, kernel)
causes[[length(causes) + 1L]] <- causes_of(rec, kernel, opts$top)
}
if (!length(shares)) stop("no recording had samples inside execute()", call. = FALSE)

shares <- bind_rows(shares)
stopifnot(all(abs(summarise(shares, t = sum(share),
.by = c(suite, benchmark, variant, run))$t - 1) < 1e-9))
write_csv(shares, opts$out, na = "")
message(sprintf("%s: %d recording(s), %d row(s)", opts$out,
nrow(distinct(shares, suite, benchmark, variant, run)),
nrow(shares)))

if (!is.null(opts$causes)) {
causes <- bind_rows(causes)
if (!nrow(causes)) {
causes <- tibble(suite = character(), benchmark = character(),
variant = character(), run = character(),
cause = character(), leaf_sym = character(),
leaf_dso = character(), samples = integer(),
share = double())
}
write_csv(causes, opts$causes, na = "")
message(sprintf("%s: %d row(s)", opts$causes, nrow(causes)))
}
}

if (sys.nframe() == 0L) main(commandArgs(trailingOnly = TRUE))
Loading
Loading