Benchmarks
Four suites compare ry’s runtime with GNU R. Two run code that others wrote: the programs that R compiler research measures itself on, and the test suites of CRAN packages. The other two run code we wrote: small numeric kernels, each also written in typed ry, and programs in the shape of package and business code. A fifth section times the three benchmark code bases, outside this summary. Each suite’s geometric mean of ry’s speed-ups over GNU R:
| Suite | What it is | ry vs GNU R | ry typed |
|---|---|---|---|
| Public R JIT benchmarks | 54 standard programs from R compiler research (Ř, rcp) | 3.76x | 20x |
| Package test suites | 26 pinned CRAN packages, each running its own test suite | 2.75x | not typed |
| Numeric kernels (ours) | 16 small programs we wrote whose time goes into loops, recursion and arithmetic on numbers | 6.06x | 26x |
| Application workloads (ours) | 15 programs we wrote in the shape of package and business code: calls, dispatch, conditions, records, tables | 3.77x | 72x |
Geometric means of the speed-ups over GNU R; above 1x means ry is faster.
- Public R JIT benchmarks: measured on 2026-11-16 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v470; 10 paired rounds.
- Package test suites: measured on 2026-11-16 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v509; 10 paired rounds.
- Benchmark code bases: measured on 2026-11-17 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v553; 10 paired rounds.
- Numeric kernels (ours): measured on 2026-11-17 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v509; 10 paired rounds.
- Application workloads (ours): measured on 2026-11-17 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v509; 10 paired rounds.
Every number on this page is rendered from the results files in tools/bench/, and each chart names
the date, the version of the engine ry is compared with, the machine and the ry commit of its
measurement.
Public R JIT benchmarks
Section titled “Public R JIT benchmarks”These are the programs that the Ř (rir) and rcp R compilers are measured on. They come from the benchmark directory of the r-compile-server repository, the suite of Kocourek, Křikava and Vitek, “Copy-and-Patch Just-in-Time Compiler for R” (VMIL 2025): all 57 but three that cannot be sized to a few seconds. The suite combines ports of Are We Fast Yet, ports of the Benchmarks Game and the rcp micro-benchmarks. They are vendored unchanged with their MIT licence, and each file ends with a driver that runs the program once at a fixed size and prints a checksum and its time. The sizes make GNU R 4.6 take about half a second to two seconds per program. Every run is a fresh process, so the time includes GNU R’s byte compilation and ry’s JIT tier-up, though not start-up.
- ry
- ry typed
mandelbrottoo short on ry typedtoo short on ry typed, AOTry: 3.57xry typed: 22xbounce_nonames_simpletoo short on ry typedtoo short on ry typed, AOTry: 2.61xry typed: 23xbounce_nonamestoo short on ry typedtoo short on ry typed, AOTry: 2.58xry typed: 22xbouncetoo short on ry typedtoo short on ry typed, AOTry: 2.24xry typed: 72xSpeed relative to GNU R on a log scale: a bar to the right of 1x is faster than GNU R, to the left slower. The line across a bar spans its 95% interval. A time marked too short on a ry engine is under 0.1 s. That speed is what the suite measures, so it counts in the geometric mean.
Measured on 2026-11-16 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v470; 10 paired rounds.
- ry
- ry typed
spectralnorm_naivetoo short on rytoo short on ry typedtoo short on ry typed, AOTwide interval on rywide interval on ry typed, AOTry: 23xry typed: 63xspectralnormtoo short on rytoo short on ry typedtoo short on ry typed, AOTwide interval on ryry: 21xry typed: 50xreversecomplement_2too short on ry typedtoo short on ry typed, AOTry: 9.88xry typed: 37xreversecomplementtoo short on ry typedtoo short on ry typed, AOTry: 7.42xry typed: 31xreversecomplement_naivetoo short on ry typedtoo short on ry typed, AOTry: 5.87xry typed: 55xfasta_naivetoo short on ry typedtoo short on ry typed, AOTry: 4.53xry typed: 33xfannkuchredux_naivetoo short on ry typedtoo short on ry typed, AOTwide interval on ry typed, AOTry: 4.37xry typed: 26xfastaredux_naivetoo short on ry typedtoo short on ry typed, AOTwide interval on rywide interval on ry typedry: 4.07xry typed: 39xfasta_3too short on ry typedtoo short on ry typed, AOTry: 3.93xry typed: 17xfasta_2too short on ry typedtoo short on ry typed, AOTry: 3.86xry typed: 13xknucleotidetoo short on ry typedtoo short on ry typed, AOTry: 3.76xry typed: 28xfasta_naive_2too short on ry typedtoo short on ry typed, AOTry: 3.40xry typed: 41xmandelbrot_naive_asciitoo short on ry typedtoo short on ry typed, AOTry: 2.71xry typed: 69xspectralnorm_alt_3too short on ry typedtoo short on ry typed, AOTwide interval on ry typed, AOTry: 2.60xry typed: 37xbinarytrees_2too short on ry typedtoo short on ry typed, AOTry: 1.70xry typed: 37xbinarytrees_naivetoo short on ry typedtoo short on ry typed, AOTry: 1.67xry typed: 54xSpeed relative to GNU R on a log scale: a bar to the right of 1x is faster than GNU R, to the left slower. The line across a bar spans its 95% interval. A time marked too short on a ry engine is under 0.1 s. That speed is what the suite measures, so it counts in the geometric mean. A program marked wide interval varied so much between rounds that its ratio's interval is wide; read its median with care.
Measured on 2026-11-16 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v470; 10 paired rounds.
- ry
- ry typed
scalar-whiletoo short on ry typedtoo short on ry typed, AOTry: 14xry typed: 21xscalar-fortoo short on ry typedtoo short on ry typed, AOTwide interval on ry typedry: 12xry typed: 42xbytecodestoo short on rytoo short on ry typedtoo short on ry typed, AOTwide interval on ry typed, AOTry: 10xry typed: 189xempty-whiletoo short on rytoo short on ry typedtoo short on ry typed, AOTwide interval on ry typedry: 8.20xry typed: 30xconvolutiontoo short on ry typedtoo short on ry typed, AOTwide interval on ryry: 7.40xry typed: 25xconvolution_slowtoo short on ry typedtoo short on ry typed, AOTry: 5.24xry typed: 34xlist-fortoo short on ry typedtoo short on ry typed, AOTry: 5.17xry typed: 102xlist-whiletoo short on ry typedtoo short on ry typed, AOTwide interval on ry typed, AOTry: 5.09xry typed: 98xsuper-whiletoo short on ry typedtoo short on ry typed, AOTwide interval on ry typedry: 4.73xry typed: 297xlapply-dotstoo short on ry typedtoo short on ry typed, AOTry: 3.33xry typed: 75xmatrix-fortoo short on ry typedtoo short on ry typed, AOTry: 3.26xry typed: 12xSpeed relative to GNU R on a log scale: a bar to the right of 1x is faster than GNU R, to the left slower. The line across a bar spans its 95% interval. A time marked too short on a ry engine is under 0.1 s. That speed is what the suite measures, so it counts in the geometric mean. A program marked wide interval varied so much between rounds that its ratio's interval is wide; read its median with care.
Measured on 2026-11-16 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v470; 10 paired rounds.
Scalar loops gain the most, because the JIT compiles them to machine code while GNU R interprets bytecode. Programs that spend their time allocating gain the least.
Each distinct algorithm also exists in typed ry, as a <name>.typed.R beside its main program, and
runs in strict mode as the ry typed column; the variants of one algorithm have
no typed version of their own. A port is written as typed ry is written, so where the R program
relies on something typed ry does not have, such as ..., <<-, matrices or complex numbers, it
uses the typed equivalent, and suite.toml notes which. Its printed output and result match GNU
R’s, so it has the same checksum. awfy storage and regexdna have no typed version, because typed
ry cannot yet express them as written.
The numbers: seconds and peak memory
| program | GNU R | ry | ry typed | ry typed, AOT | ry, speed-up | ry typed, speed-up | ry typed, AOT, speed-up |
|---|---|---|---|---|---|---|---|
| Bouncing balls, named fields | 1.121 s | 0.490 s | 0.015 s | 0.015 s | 2.24x (2.10x to 2.40x) | 72x (68x to 76x) (too short on ry typed) | 72x (70x to 74x) (too short on ry typed, AOT) |
| Bouncing balls, positional fields | 1.095 s | 0.421 s | 0.051 s | 0.048 s | 2.58x (2.44x to 2.73x) | 22x (20x to 23x) (too short on ry typed) | 22x (21x to 23x) (too short on ry typed, AOT) |
| Bouncing balls, positional fields, simple setup | 1.127 s | 0.422 s | 0.049 s | 0.048 s | 2.61x (2.49x to 2.82x) | 23x (21x to 24x) (too short on ry typed) | 22x (22x to 24x) (too short on ry typed, AOT) |
| Mandelbrot set, scalar loops | 1.159 s | 0.326 s | 0.052 s | 0.052 s | 3.57x (3.36x to 3.72x) | 22x (21x to 23x) (too short on ry typed) | 22x (21x to 23x) (too short on ry typed, AOT) |
| Tree allocation | 1.239 s | 0.386 s | 0.028 s | 0.029 s | 3.15x (2.94x to 3.23x) | 44x (40x to 45x) (too short on ry typed) | 43x (40x to 45x) (too short on ry typed, AOT) |
| Binary trees | 1.784 s | 0.942 s | 0.033 s | 0.032 s | 1.87x (1.80x to 1.97x) | 53x (51x to 56x) (too short on ry typed) | 57x (54x to 58x) (too short on ry typed, AOT) |
| Binary trees, inline arithmetic | 0.685 s | 0.393 s | 0.018 s | 0.019 s | 1.70x (1.68x to 1.81x) | 37x (35x to 39x) (too short on ry typed) | 37x (33x to 38x) (too short on ry typed, AOT) |
| Binary trees, explicit loop | 1.683 s | 0.996 s | 0.031 s | 0.031 s | 1.67x (1.61x to 1.75x) | 54x (52x to 56x) (too short on ry typed) | 53x (51x to 55x) (too short on ry typed, AOT) |
| Fannkuch-redux | 2.766 s | 1.673 s | 0.143 s | 0.141 s | 1.66x (1.58x to 1.73x) | 20x (18x to 21x) | 20x (18x to 21x) |
| Fannkuch-redux, scalar swaps | 1.390 s | 0.314 s | 0.050 s | 0.053 s | 4.37x (4.04x to 4.56x) | 26x (24x to 28x) (too short on ry typed) | 25x (20x to 28x) (too short on ry typed, AOT, wide interval on ry typed, AOT) |
| Fasta | 0.959 s | 0.279 s | 0.047 s | 0.048 s | 3.43x (3.12x to 3.60x) | 21x (20x to 21x) (too short on ry typed) | 20x (19x to 20x) (too short on ry typed, AOT) |
| Fasta, vectorized linear search | 1.032 s | 0.268 s | 0.077 s | 0.073 s | 3.86x (3.60x to 4.02x) | 13x (12x to 13x) (too short on ry typed) | 14x (13x to 14x) (too short on ry typed, AOT) |
| Fasta, vectorized binary search | 1.262 s | 0.318 s | 0.077 s | 0.080 s | 3.93x (3.70x to 4.09x) | 17x (16x to 17x) (too short on ry typed) | 16x (15x to 16x) (too short on ry typed, AOT) |
| Fasta, scalar linear search | 1.500 s | 0.323 s | 0.044 s | 0.049 s | 4.53x (4.43x to 4.72x) | 33x (33x to 34x) (too short on ry typed) | 30x (29x to 31x) (too short on ry typed, AOT) |
| Fasta, scalar binary search | 2.100 s | 0.603 s | 0.051 s | 0.055 s | 3.40x (3.25x to 3.60x) | 41x (38x to 42x) (too short on ry typed) | 38x (37x to 39x) (too short on ry typed, AOT) |
| Fasta-redux | 1.206 s | 0.257 s | 0.046 s | 0.049 s | 4.72x (4.60x to 4.82x) | 26x (25x to 27x) (too short on ry typed) | 24x (22x to 25x) (too short on ry typed, AOT) |
| Fasta-redux, scalar lookup | 1.431 s | 0.346 s | 0.035 s | 0.037 s | 4.07x (3.63x to 4.22x) (wide interval on ry) | 39x (35x to 43x) (too short on ry typed, wide interval on ry typed) | 38x (37x to 39x) (too short on ry typed, AOT) |
| K-nucleotide, hashed environment | 1.245 s | 0.336 s | 0.044 s | 0.055 s | 3.76x (3.63x to 3.96x) | 28x (27x to 29x) (too short on ry typed) | 22x (21x to 23x) (too short on ry typed, AOT) |
| K-nucleotide, attribute counts | 0.834 s | 0.205 s | 0.183 s | 0.208 s | 4.17x (3.92x to 4.24x) | 4.49x (4.39x to 4.73x) | 4.10x (3.71x to 4.26x) |
| K-nucleotide, attribute counts, growing vector | 1.308 s | 0.435 s | 0.296 s | 0.310 s | 3.00x (2.98x to 3.06x) | 4.39x (4.19x to 4.51x) | 4.20x (4.06x to 4.36x) |
| K-nucleotide, named vector counts | 1.319 s | 0.237 s | 0.280 s | 0.278 s | 5.52x (5.15x to 6.04x) | 4.76x (4.38x to 4.93x) | 4.75x (4.63x to 5.21x) |
| Mandelbrot, vectorized rows | 0.939 s | 0.602 s | 0.577 s | 0.554 s | 1.58x (1.51x to 1.63x) | 1.64x (1.47x to 1.69x) (wide interval on ry typed) | 1.69x (1.61x to 1.75x) |
| Mandelbrot, scalar points | 1.682 s | 0.624 s | 0.024 s | 0.024 s | 2.71x (2.50x to 2.75x) | 69x (67x to 72x) (too short on ry typed) | 70x (66x to 72x) (too short on ry typed, AOT) |
| Mandelbrot, vectorized rows, no output | 0.734 s | 0.464 s | 0.467 s | 0.463 s | 1.60x (1.56x to 1.65x) | 1.58x (1.53x to 1.65x) | 1.54x (1.51x to 1.66x) |
| Mandelbrot, whole-plane matrix | 1.094 s | 0.811 s | 0.505 s | 0.517 s | 1.36x (1.27x to 1.40x) | 2.15x (2.07x to 2.22x) | 2.15x (2.05x to 2.22x) |
| N-body | 1.476 s | 0.782 s | 0.019 s | 0.020 s | 1.87x (1.81x to 1.97x) | 75x (71x to 78x) (too short on ry typed) | 74x (70x to 78x) (too short on ry typed, AOT) |
| N-body, matrix state | 1.480 s | 0.812 s | 0.102 s | 0.110 s | 1.82x (1.73x to 1.95x) | 14x (13x to 15x) | 13x (13x to 15x) |
| Pi digits | 0.811 s | 0.286 s | 0.050 s | 0.057 s | 2.78x (2.58x to 2.89x) | 16x (15x to 17x) (too short on ry typed) | 14x (14x to 15x) (too short on ry typed, AOT) |
| Regex DNA | 1.014 s | 0.331 s | 1.041 s | 1.047 s | 3.07x (2.96x to 3.33x) | 0.97x (0.95x to 1.01x) | 0.96x (0.90x to 1.00x) |
| Reverse complement | 0.833 s | 0.113 s | 0.026 s | 0.027 s | 7.42x (6.95x to 7.61x) | 31x (29x to 34x) (too short on ry typed) | 31x (29x to 33x) (too short on ry typed, AOT) |
| Reverse complement, whole file | 1.171 s | 0.116 s | 0.032 s | 0.033 s | 9.88x (9.57x to 10x) | 37x (35x to 38x) (too short on ry typed) | 35x (34x to 39x) (too short on ry typed, AOT) |
| Reverse complement, scalar lookup | 1.768 s | 0.292 s | 0.031 s | 0.032 s | 5.87x (5.70x to 6.22x) | 55x (54x to 58x) (too short on ry typed) | 54x (51x to 57x) (too short on ry typed, AOT) |
| Spectral norm | 1.637 s | 0.068 s | 0.031 s | 0.044 s | 21x (20x to 24x) (too short on ry, wide interval on ry) | 50x (46x to 55x) (too short on ry typed) | 36x (33x to 38x) (too short on ry typed, AOT) |
| Spectral norm, precomputed matrix | 1.355 s | 0.625 s | 0.732 s | 0.727 s | 2.14x (2.10x to 2.22x) | 1.83x (1.75x to 1.91x) | 1.78x (1.73x to 1.86x) |
| Spectral norm, matrix rebuilt per product | 2.120 s | 0.731 s | 0.936 s | 0.930 s | 3.05x (2.82x to 3.09x) | 2.32x (2.10x to 2.39x) | 2.28x (2.21x to 2.33x) |
| Spectral norm, element-wise matrix fill | 2.137 s | 0.840 s | 0.058 s | 0.060 s | 2.60x (2.41x to 2.69x) | 37x (34x to 38x) (too short on ry typed) | 37x (33x to 38x) (too short on ry typed, AOT, wide interval on ry typed, AOT) |
| Spectral norm, eigenvalues | 1.681 s | 1.462 s | 2.281 s | 2.326 s | 1.16x (1.11x to 1.19x) | 0.74x (0.72x to 0.75x) | 0.72x (0.70x to 0.75x) |
| Spectral norm, scalar loops | 1.571 s | 0.069 s | 0.024 s | 0.027 s | 23x (20x to 26x) (too short on ry, wide interval on ry) | 63x (59x to 68x) (too short on ry typed) | 55x (52x to 65x) (too short on ry typed, AOT, wide interval on ry typed, AOT) |
| Many local assignments | 0.574 s | 0.055 s | 0.003 s | 0.003 s | 10x (9.95x to 11x) (too short on ry) | 189x (184x to 199x) (too short on ry typed) | 193x (155x to 210x) (too short on ry typed, AOT, wide interval on ry typed, AOT) |
| Convolution, scalar loops | 0.966 s | 0.134 s | 0.037 s | 0.038 s | 7.40x (6.57x to 7.58x) (wide interval on ry) | 25x (25x to 27x) (too short on ry typed) | 25x (24x to 26x) (too short on ry typed, AOT) |
| Convolution, [[ indexing | 1.044 s | 0.193 s | 0.030 s | 0.031 s | 5.24x (5.10x to 5.54x) | 34x (32x to 36x) (too short on ry typed) | 35x (33x to 35x) (too short on ry typed, AOT) |
| Convolution, vectorized | 1.593 s | 1.002 s | 0.289 s | 0.276 s | 1.60x (1.51x to 1.62x) | 5.55x (5.35x to 5.77x) | 5.75x (5.44x to 5.90x) |
| Empty for loop | 0.751 s | 0.183 s | 0.074 s | 0.075 s | 4.11x (4.02x to 4.23x) | 10x (10x to 10x) (too short on ry typed) | 10x (9.64x to 10x) (too short on ry typed, AOT) |
| Counting while loop | 0.507 s | 0.061 s | 0.017 s | 0.017 s | 8.20x (7.82x to 8.56x) (too short on ry) | 30x (25x to 32x) (too short on ry typed, wide interval on ry typed) | 30x (28x to 31x) (too short on ry typed, AOT) |
| lapply with a closure | 0.919 s | 0.264 s | 0.015 s | 0.015 s | 3.47x (3.35x to 3.53x) | 61x (57x to 63x) (too short on ry typed) | 60x (55x to 61x) (too short on ry typed, AOT) |
| lapply with an extra argument | 1.165 s | 0.345 s | 0.016 s | 0.016 s | 3.33x (3.28x to 3.44x) | 75x (71x to 79x) (too short on ry typed) | 74x (71x to 77x) (too short on ry typed, AOT) |
| Growing a list, for loop | 1.192 s | 0.231 s | 0.011 s | 0.012 s | 5.17x (5.06x to 5.28x) | 102x (93x to 104x) (too short on ry typed) | 99x (93x to 106x) (too short on ry typed, AOT) |
| Growing a list, while loop | 1.244 s | 0.243 s | 0.012 s | 0.013 s | 5.09x (4.85x to 5.15x) | 98x (94x to 104x) (too short on ry typed) | 98x (88x to 104x) (too short on ry typed, AOT, wide interval on ry typed, AOT) |
| Matrix element assignment | 0.658 s | 0.199 s | 0.054 s | 0.054 s | 3.26x (3.20x to 3.44x) | 12x (12x to 13x) (too short on ry typed) | 12x (12x to 13x) (too short on ry typed, AOT) |
| Scalar assignment, for loop | 1.696 s | 0.138 s | 0.039 s | 0.038 s | 12x (12x to 13x) | 42x (35x to 44x) (too short on ry typed, wide interval on ry typed) | 44x (42x to 46x) (too short on ry typed, AOT) |
| Scalar assignment, while loop | 1.534 s | 0.115 s | 0.075 s | 0.075 s | 14x (13x to 14x) | 21x (20x to 22x) (too short on ry typed) | 20x (20x to 22x) (too short on ry typed, AOT) |
| Superassignment loop | 1.525 s | 0.318 s | 0.005 s | 0.006 s | 4.73x (4.55x to 4.87x) | 297x (245x to 305x) (too short on ry typed, wide interval on ry typed) | 273x (248x to 276x) (too short on ry typed, AOT) |
| Vector element assignment, for loop | 1.139 s | 0.322 s | 0.143 s | 0.146 s | 3.51x (3.31x to 3.71x) | 7.89x (7.61x to 8.07x) | 7.70x (7.35x to 8.02x) |
| Vector element assignment, while loop | 1.183 s | 0.164 s | 0.142 s | 0.142 s | 6.90x (6.23x to 7.22x) | 8.21x (7.84x to 8.49x) | 7.88x (7.68x to 8.27x) |
Each time is the median over the rounds. Each speed-up is the median of the per-round ratios, with its 95% interval in parentheses. ry typed, AOT compiles each typed function before the program starts. Its time is the program's clock plus that compile, so it counts the same work as the other columns.
| program | GNU R | ry | ry typed | ry typed, AOT |
|---|---|---|---|---|
| Bouncing balls, named fields | 75 MiB | 81 MiB | 56 MiB | 56 MiB |
| Bouncing balls, positional fields | 87 MiB | 74 MiB | 58 MiB | 58 MiB |
| Bouncing balls, positional fields, simple setup | 87 MiB | 72 MiB | 59 MiB | 59 MiB |
| Mandelbrot set, scalar loops | 70 MiB | 65 MiB | 52 MiB | 56 MiB |
| Tree allocation | 104 MiB | 88 MiB | 70 MiB | 68 MiB |
| Binary trees | 74 MiB | 63 MiB | 57 MiB | 58 MiB |
| Binary trees, inline arithmetic | 70 MiB | 58 MiB | 54 MiB | 52 MiB |
| Binary trees, explicit loop | 76 MiB | 65 MiB | 57 MiB | 56 MiB |
| Fannkuch-redux | 73 MiB | 78 MiB | 56 MiB | 57 MiB |
| Fannkuch-redux, scalar swaps | 76 MiB | 79 MiB | 56 MiB | 53 MiB |
| Fasta | 126 MiB | 82 MiB | 75 MiB | 80 MiB |
| Fasta, vectorized linear search | 118 MiB | 80 MiB | 82 MiB | 82 MiB |
| Fasta, vectorized binary search | 121 MiB | 81 MiB | 83 MiB | 83 MiB |
| Fasta, scalar linear search | 127 MiB | 94 MiB | 92 MiB | 93 MiB |
| Fasta, scalar binary search | 115 MiB | 89 MiB | 91 MiB | 92 MiB |
| Fasta-redux | 140 MiB | 87 MiB | 92 MiB | 94 MiB |
| Fasta-redux, scalar lookup | 130 MiB | 96 MiB | 91 MiB | 89 MiB |
| K-nucleotide, hashed environment | 72 MiB | 78 MiB | 75 MiB | 75 MiB |
| K-nucleotide, attribute counts | 70 MiB | 62 MiB | 71 MiB | 71 MiB |
| K-nucleotide, attribute counts, growing vector | 70 MiB | 63 MiB | 70 MiB | 67 MiB |
| K-nucleotide, named vector counts | 129 MiB | 64 MiB | 61 MiB | 61 MiB |
| Mandelbrot, vectorized rows | 124 MiB | 93 MiB | 80 MiB | 81 MiB |
| Mandelbrot, scalar points | 138 MiB | 60 MiB | 51 MiB | 54 MiB |
| Mandelbrot, vectorized rows, no output | 124 MiB | 66 MiB | 56 MiB | 59 MiB |
| Mandelbrot, whole-plane matrix | 405 MiB | 413 MiB | 255 MiB | 255 MiB |
| N-body | 69 MiB | 60 MiB | 54 MiB | 52 MiB |
| N-body, matrix state | 72 MiB | 60 MiB | 68 MiB | 69 MiB |
| Pi digits | 69 MiB | 72 MiB | 67 MiB | 67 MiB |
| Regex DNA | 118 MiB | 101 MiB | 139 MiB | 139 MiB |
| Reverse complement | 147 MiB | 98 MiB | 101 MiB | 102 MiB |
| Reverse complement, whole file | 156 MiB | 105 MiB | 112 MiB | 113 MiB |
| Reverse complement, scalar lookup | 150 MiB | 101 MiB | 112 MiB | 113 MiB |
| Spectral norm | 69 MiB | 69 MiB | 59 MiB | 56 MiB |
| Spectral norm, precomputed matrix | 309 MiB | 194 MiB | 197 MiB | 197 MiB |
| Spectral norm, matrix rebuilt per product | 168 MiB | 74 MiB | 126 MiB | 128 MiB |
| Spectral norm, element-wise matrix fill | 79 MiB | 69 MiB | 69 MiB | 68 MiB |
| Spectral norm, eigenvalues | 126 MiB | 106 MiB | 83 MiB | 84 MiB |
| Spectral norm, scalar loops | 69 MiB | 61 MiB | 53 MiB | 54 MiB |
| Many local assignments | 82 MiB | 64 MiB | 54 MiB | 55 MiB |
| Convolution, scalar loops | 70 MiB | 62 MiB | 56 MiB | 57 MiB |
| Convolution, [[ indexing | 69 MiB | 64 MiB | 52 MiB | 57 MiB |
| Convolution, vectorized | 186 MiB | 123 MiB | 224 MiB | 225 MiB |
| Empty for loop | 63 MiB | 52 MiB | 54 MiB | 55 MiB |
| Counting while loop | 64 MiB | 53 MiB | 52 MiB | 55 MiB |
| lapply with a closure | 187 MiB | 155 MiB | 195 MiB | 196 MiB |
| lapply with an extra argument | 185 MiB | 155 MiB | 195 MiB | 196 MiB |
| Growing a list, for loop | 220 MiB | 184 MiB | 66 MiB | 65 MiB |
| Growing a list, while loop | 220 MiB | 188 MiB | 67 MiB | 68 MiB |
| Matrix element assignment | 166 MiB | 161 MiB | 118 MiB | 118 MiB |
| Scalar assignment, for loop | 75 MiB | 50 MiB | 52 MiB | 55 MiB |
| Scalar assignment, while loop | 76 MiB | 55 MiB | 54 MiB | 55 MiB |
| Superassignment loop | 77 MiB | 60 MiB | 53 MiB | 55 MiB |
| Vector element assignment, for loop | 292 MiB | 169 MiB | 278 MiB | 279 MiB |
| Vector element assignment, while loop | 140 MiB | 136 MiB | 202 MiB | 202 MiB |
Peak memory is the peak resident set size of the whole process, R's startup included.
Measured on 2026-11-16 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v470; 10 paired rounds.
Are We Fast Yet. R translations of programs from the Are We Fast Yet suite, which compares language implementations on the same small object and loop workloads. Bounce comes in three variants that differ in how a ball's fields are indexed. Source: github.com/PRL-PRG/r-compile-server/tree/b2b13a3150bddcc2d6dae8c37ecbbf1007170940/client/rsh/inst/benchmarks/areWeFast, MIT.
Bouncing balls, named fields bounce 2.24x
Moves 3,000 balls for 50 steps with lapply, reading and writing each ball's fields by name (ball['xVel']) Source
source('random.r')
execute <- function (ballCount = 3000L) { bounces <- 0 balls = vector("list", length = ballCount) resetSeed()
for (i in 1:ballCount) { balls[[i]] = c(nextRandom() %% 500, nextRandom() %% 500, (nextRandom() %% 300) - 150, (nextRandom() %% 300) - 150) names(balls[[i]]) = c("x", "y", "xVel", "yVel") }
ball <- function(ball) { results <- bounce(ball) if (results[[2]]) bounces <<- bounces + 1 return (results[[1]]) }
for (i in 1:50) balls <- lapply(balls, ball) return (bounces)}
bounce <- function(ball) { xLimit <- 500 yLimit <- 500 bounced <- FALSE
ball['x'] <- ball['x'] + ball['xVel']; ball['y'] <- ball['y'] + ball['yVel'];
if (ball['x'] > xLimit) { ball['x'] <- xLimit ball['xVel'] <- 0 - abs(ball['xVel']) bounced <- TRUE } if (ball['x'] < 0) { ball['x'] <- 0 ball['xVel'] <- abs(ball['xVel']) bounced <- TRUE } if (ball['y'] > yLimit) { ball['y'] <- yLimit ball['yVel'] <- 0 - abs(ball['yVel']) bounced <- TRUE } if (ball['y'] < 0) { ball['y'] <- 0 ball['yVel'] <- abs(ball['yVel']) bounced <- TRUE } return (list(ball, bounced))}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(3000L)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("bounce %s %.4f\n", checksum, seconds))})alias Ball = Record{x: F64, y: F64, x_vel: F64, y_vel: F64}
execute <- function(ball_count: I64) -> F64 { seed <- 74755 next_random <- function(seed: I64) -> I64 Num.bitwise_and(seed * 1309 + 13849, 65535)
balls <- [] for (i in List.range(1, ball_count)) { seed <- next_random(seed) x <- seed %% 500 seed <- next_random(seed) y <- seed %% 500 seed <- next_random(seed) x_vel <- seed %% 300 - 150 seed <- next_random(seed) y_vel <- seed %% 300 - 150 ball <- (x = Num.to_f64(x), y = Num.to_f64(y), x_vel = Num.to_f64(x_vel), y_vel = Num.to_f64(y_vel)) balls <- List.append(balls, ball) }
bounces <- 0 for (i in List.range(1, 50)) { moved <- List.map(balls, bounce) bounces <- bounces + Num.to_f64(List.count_if(moved, \(m) m$bounced)) balls <- List.map(moved, \(m) m$ball) } bounces}
bounce <- function(ball: Ball) -> Record{ball: Ball, bounced: Bool} { x_limit <- 500 y_limit <- 500 bounced <- Bool.false
ball <- (..ball, x = ball$x + ball$x_vel, y = ball$y + ball$y_vel)
if (ball$x > x_limit) { ball <- (..ball, x = x_limit, x_vel = 0 - Num.abs(ball$x_vel)) bounced <- Bool.true } if (ball$x < 0) { ball <- (..ball, x = 0, x_vel = Num.abs(ball$x_vel)) bounced <- Bool.true } if (ball$y > y_limit) { ball <- (..ball, y = y_limit, y_vel = 0 - Num.abs(ball$y_vel)) bounced <- Bool.true } if (ball$y < 0) { ball <- (..ball, y = 0, y_vel = Num.abs(ball$y_vel)) bounced <- Bool.true } (ball = ball, bounced = bounced)}
# ---------------------------------------------------------------------------# Driver: the same as bounce.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(3000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("bounce %s %.4f\n", checksum, seconds))})Bouncing balls, positional fields bounce_nonames 2.58x
Moves 10,000 balls for 50 steps with lapply, indexing each ball's fields by position and counting bounces through <<- Source
execute <- function (unused) { seed <- NaN
resetSeed <- function() seed <<- 74755
nextRandom <- function() { seed <<- bitwAnd((seed * 1309) + 13849, 65535) return (seed) }
ballCount <- 10000 bounces <- 0 balls = vector("list", length = ballCount) resetSeed()
for (i in 1:ballCount) { balls[[i]] = c(nextRandom() %% 500, nextRandom() %% 500, (nextRandom() %% 300) - 150, (nextRandom() %% 300) - 150) }
ball <- function(ball) { results <- bounce(ball) if (results[[2]]) bounces <<- bounces + 1 return (results[[1]]) }
for (i in 1:50) balls <- lapply(balls, ball) return (bounces)}
bounce <- function(ball) { xLimit <- 500 yLimit <- 500 bounced <- FALSE
ball[1] <- ball[1] + ball[3]; ball[2] <- ball[2] + ball[4];
if (ball[1] > xLimit) { ball[1] <- xLimit ball[3] <- 0 - abs(ball[3]) bounced <- TRUE } if (ball[1] < 0) { ball[1] <- 0 ball[3] <- abs(ball[3]) bounced <- TRUE } if (ball[2] > yLimit) { ball[2] <- yLimit ball[4] <- 0 - abs(ball[4]) bounced <- TRUE } if (ball[2] < 0) { ball[2] <- 0 ball[4] <- abs(ball[4]) bounced <- TRUE } return (list(ball, bounced))}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(NULL)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("bounce_nonames %s %.4f\n", checksum, seconds))})execute <- function(ball_count: I64) -> F64 { seed <- 74755 next_random <- function(seed: I64) -> I64 Num.bitwise_and(seed * 1309 + 13849, 65535)
balls <- [] for (i in List.range(1, ball_count)) { seed <- next_random(seed) x <- seed %% 500 seed <- next_random(seed) y <- seed %% 500 seed <- next_random(seed) x_vel <- seed %% 300 - 150 seed <- next_random(seed) y_vel <- seed %% 300 - 150 balls <- List.append(balls, [Num.to_f64(x), Num.to_f64(y), Num.to_f64(x_vel), Num.to_f64(y_vel)]) }
bounces <- 0 for (i in List.range(1, 50)) { moved <- List.map(balls, bounce) bounces <- bounces + Num.to_f64(List.count_if(moved, \(m) m[[2]])) balls <- List.map(moved, \(m) m[[1]]) } bounces}
bounce <- function(ball: List<F64>) -> Tuple{List<F64>, Bool} { x_limit <- 500 y_limit <- 500 bounced <- Bool.false
ball[[1]] <- ball[[1]] + ball[[3]] ball[[2]] <- ball[[2]] + ball[[4]]
if (ball[[1]] > x_limit) { ball[[1]] <- x_limit ball[[3]] <- 0 - Num.abs(ball[[3]]) bounced <- Bool.true } if (ball[[1]] < 0) { ball[[1]] <- 0 ball[[3]] <- Num.abs(ball[[3]]) bounced <- Bool.true } if (ball[[2]] > y_limit) { ball[[2]] <- y_limit ball[[4]] <- 0 - Num.abs(ball[[4]]) bounced <- Bool.true } if (ball[[2]] < 0) { ball[[2]] <- 0 ball[[4]] <- Num.abs(ball[[4]]) bounced <- Bool.true } (ball, bounced)}
# ---------------------------------------------------------------------------# Driver: the same as bounce_nonames.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(10000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("bounce_nonames %s %.4f\n", checksum, seconds))})Bouncing balls, positional fields, simple setup bounce_nonames_simple 2.61x
Same as the positional variant, but each ball's four random numbers are drawn into locals before c() builds it Source
execute <- function (unused) { seed <- NaN
resetSeed <- function() seed <<- 74755
nextRandom <- function() { seed <<- bitwAnd((seed * 1309) + 13849, 65535) return (seed) }
ballCount <- 10000 bounces <- 0 balls = vector("list", length = ballCount) resetSeed()
for (i in 1:ballCount) { random1 <- nextRandom() random2 <- nextRandom() random3 <- nextRandom() random4 <- nextRandom() balls[[i]] = c(random1 %% 500, random2 %% 500, (random3 %% 300) - 150, (random4 %% 300) - 150) }
ball <- function(ball) { results <- bounce(ball) if (results[[2]]) bounces <<- bounces + 1 return (results[[1]]) }
for (i in 1:50) balls <- lapply(balls, ball) return (bounces)}
bounce <- function(ball) { xLimit <- 500 yLimit <- 500 bounced <- FALSE
ball[1] <- ball[1] + ball[3]; ball[2] <- ball[2] + ball[4];
if (ball[1] > xLimit) { ball[1] <- xLimit ball[3] <- 0 - abs(ball[3]) bounced <- TRUE } if (ball[1] < 0) { ball[1] <- 0 ball[3] <- abs(ball[3]) bounced <- TRUE } if (ball[2] > yLimit) { ball[2] <- yLimit ball[4] <- 0 - abs(ball[4]) bounced <- TRUE } if (ball[2] < 0) { ball[2] <- 0 ball[4] <- abs(ball[4]) bounced <- TRUE } return (list(ball, bounced))}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(NULL)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("bounce_nonames_simple %s %.4f\n", checksum, seconds))})execute <- function(ball_count: I64) -> F64 { seed <- 74755 next_random <- function(seed: I64) -> I64 Num.bitwise_and(seed * 1309 + 13849, 65535)
balls <- [] for (i in List.range(1, ball_count)) { seed <- next_random(seed) x <- seed %% 500 seed <- next_random(seed) y <- seed %% 500 seed <- next_random(seed) x_vel <- seed %% 300 - 150 seed <- next_random(seed) y_vel <- seed %% 300 - 150 balls <- List.append(balls, [Num.to_f64(x), Num.to_f64(y), Num.to_f64(x_vel), Num.to_f64(y_vel)]) }
bounces <- 0 for (i in List.range(1, 50)) { moved <- List.map(balls, bounce) bounces <- bounces + Num.to_f64(List.count_if(moved, \(m) m[[2]])) balls <- List.map(moved, \(m) m[[1]]) } bounces}
bounce <- function(ball: List<F64>) -> Tuple{List<F64>, Bool} { x_limit <- 500 y_limit <- 500 bounced <- Bool.false
ball[[1]] <- ball[[1]] + ball[[3]] ball[[2]] <- ball[[2]] + ball[[4]]
if (ball[[1]] > x_limit) { ball[[1]] <- x_limit ball[[3]] <- 0 - Num.abs(ball[[3]]) bounced <- Bool.true } if (ball[[1]] < 0) { ball[[1]] <- 0 ball[[3]] <- Num.abs(ball[[3]]) bounced <- Bool.true } if (ball[[2]] > y_limit) { ball[[2]] <- y_limit ball[[4]] <- 0 - Num.abs(ball[[4]]) bounced <- Bool.true } if (ball[[2]] < 0) { ball[[2]] <- 0 ball[[4]] <- Num.abs(ball[[4]]) bounced <- Bool.true } (ball, bounced)}
# ---------------------------------------------------------------------------# Driver: the same as bounce_nonames.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(10000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("bounce_nonames %s %.4f\n", checksum, seconds))})Mandelbrot set, scalar loops mandelbrot 3.57x
Computes a 450 x 450 Mandelbrot bitmap checksum with nested scalar while loops, double arithmetic and bitwShiftL/bitwXor Source
lim <- 2iter <- 50
execute <- function(size=450L) { sum = 0 byteAcc = 0 bitNum = 0
y = 0
while (y < size) { ci = (2.0 * y / size) - 1.0 x = 0
while (x < size) { zr = 0.0 zrzr = 0.0 zi = 0.0 zizi = 0.0 cr = (2.0 * x / size) - 1.5
z = 0 notDone = TRUE escape = 0 while (notDone && (z < 50)) { zr = zrzr - zizi + cr zi = 2.0 * zr * zi + ci
# preserve recalculation zrzr = zr * zr zizi = zi * zi
if ((zrzr + zizi) > 4.0) { notDone = FALSE escape = 1 } z = z + 1 }
byteAcc = bitwShiftL(byteAcc, 1) + escape
bitNum = bitNum + 1
# Code is very similar for these cases, but using separate blocks # ensures we skip the shifting when it's unnecessary, which is most cases. if (bitNum == 8) { sum = bitwXor(sum, byteAcc) byteAcc = 0 bitNum = 0 } else if (x == (size - 1)) { byteAcc = bitwShiftL(byteAcc, 8 - bitNum) sum = bitwXor(sum, byteAcc) byteAcc = 0 bitNum = 0 } x = x + 1 } y = y + 1 } return (sum);}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(450L)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("mandelbrot %s %.4f\n", checksum, seconds))})execute <- function(size: I64) -> I64 { sum <- 0 byte_acc <- 0 bit_num <- 0i64 fsize <- Num.to_f64(size)
y <- 0 while (y < size) { ci <- (2.0 * Num.to_f64(y) / fsize) - 1.0 x <- 0
while (x < size) { zr <- 0.0 zrzr <- 0.0 zi <- 0.0 zizi <- 0.0 cr <- (2.0 * Num.to_f64(x) / fsize) - 1.5
z <- 0 not_done <- Bool.true escape <- 0i64 while (not_done && (z < 50)) { zr <- zrzr - zizi + cr zi <- 2.0 * zr * zi + ci
# preserve recalculation zrzr <- zr * zr zizi <- zi * zi
if ((zrzr + zizi) > 4.0) { not_done <- Bool.false escape <- 1i64 } z <- z + 1 }
byte_acc <- Num.shift_left_by(byte_acc, 1) + escape
bit_num <- bit_num + 1
# Code is very similar for these cases, but using separate blocks # ensures we skip the shifting when it's unnecessary, which is most cases. if (bit_num == 8) { sum <- Num.bitwise_xor(sum, byte_acc) byte_acc <- 0i64 bit_num <- 0i64 } else if (x == (size - 1)) { byte_acc <- Num.shift_left_by(byte_acc, 8 - bit_num) sum <- Num.bitwise_xor(sum, byte_acc) byte_acc <- 0i64 bit_num <- 0i64 } x <- x + 1 } y <- y + 1 } sum}
# ---------------------------------------------------------------------------# Driver: the same as mandelbrot.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- Num.to_r(execute(450))) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("mandelbrot %s %.4f\n", checksum, seconds))})Tree allocation storage 3.15x
Recursively builds a depth-10 tree of 4-element lists with random leaves, stressing allocation, recursion and <<- Source
source('random.r')
count <- 0
execute <- function(size) { buildTreeDepth <- function(depth, random) { count <<- count + 1 if (depth == 1) { return (c(nextRandom() %% 10 + 1)) } else { array <- vector("list", length = 4) for (i in 1:4) { array[[i]] <- buildTreeDepth(depth - 1, random) } return (array) } }
count <<- 0 resetSeed() buildTreeDepth(10, nextRandom()) return (count)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(NULL)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("storage %s %.4f\n", checksum, seconds))})type Tree = :Leaf(I64) | :Node(List<Tree>)
execute <- function() -> F64 { built <- build_tree(10, 74755, 0) Num.to_f64(built$count)}
build_tree <- function(depth: I64, seed: I64, count: I64) -> Record{tree: Tree, seed: I64, count: I64} { count <- count + 1 if (depth == 1) { seed <- Num.bitwise_and(seed * 1309 + 13849, 65535) return((tree = @Tree(:Leaf(seed %% 10 + 1)), seed = seed, count = count)) } children <- [] for (i in List.range(1, 4)) { built <- build_tree(depth - 1, seed, count) children <- List.append(children, built$tree) seed <- built$seed count <- built$count } (tree = @Tree(:Node(children)), seed = seed, count = count)}
# ---------------------------------------------------------------------------# Driver: the same as storage.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute()) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("storage %s %.4f\n", checksum, seconds))})Benchmarks Game. R ports of the Computer Language Benchmarks Game programs, each in several variants that range from idiomatic vectorized R to naive scalar loops. The input-reading programs read a FASTA file that the driver generates with fasta.R before timing starts. Source: github.com/PRL-PRG/r-compile-server/tree/b2b13a3150bddcc2d6dae8c37ecbbf1007170940/client/rsh/inst/benchmarks/shootout, MIT.
Binary trees binarytrees 1.87x
Allocates and walks recursive list trees up to depth 12, with integer arithmetic and sapply over the iterations Source
execute <- function(n=9) { tree <- function(item, depth) { if (depth == 0L) return(c(item, NA, NA)) # it is ridiculous that this doesn't help next_depth <- depth - 1L right_item <- 2L * item left_item <- right_item - 1L return(list(item, tree(left_item, next_depth), tree(right_item, next_depth))) }
check <- function(tree) if(is.na(tree[[2]][[1]])) tree[[1]] else tree[[1]] + check(tree[[2]]) - check(tree[[3]])
binarytrees <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 13L
min_depth <- 4L max_depth <- max(min_depth + 2L, n) stretch_depth <- max_depth + 1L
cat(sep="", "stretch tree of depth ", stretch_depth, "\t check: ", check(tree(0L, stretch_depth)), "\n")
long_lived_tree <- tree(0L, max_depth)
for (depth in seq(min_depth, max_depth, 2L)) { iterations <- as.integer(2^(max_depth - depth + min_depth)) check_sum <- sum(sapply( 1:iterations, function(i) check(tree(i, depth)) + check(tree(-i, depth)))) cat(sep="", iterations * 2L, "\t trees of depth ", depth, "\t check: ", check_sum, "\n") }
cat(sep="", "long lived tree of depth ", max_depth, "\t check: ", check(long_lived_tree), "\n") }
binarytrees(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(12)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("binarytrees %s %.4f\n", checksum, seconds))})type Tree = :Leaf(I64) | :Node(item: I64, left: Tree, right: Tree)
tree <- function(item: I64, depth: I64) -> Tree { if (depth == 0) return(@Tree(:Leaf(item))) next_depth <- depth - 1 right_item <- 2 * item left_item <- right_item - 1 @Tree(:Node(item = item, left = tree(left_item, next_depth), right = tree(right_item, next_depth)))}
check <- function(tree: Tree) -> I64 { match (tree) { :Leaf(item) => item :Node(item = item, left = left, right = right) => item + check(left) - check(right) }}
execute <- function(n: I64) -> List<Str> { min_depth: I64 <- 4 max_depth <- Num.max(min_depth + 2, n) stretch_depth <- max_depth + 1
lines <- [f"stretch tree of depth {stretch_depth}\t check: {check(tree(0, stretch_depth))}\n"]
long_lived_tree <- tree(0, max_depth)
depth <- min_depth while (depth <= max_depth) { iterations <- Num.pow_int(2, max_depth - depth + min_depth) check_sum <- List.sum(List.map(List.range(1, iterations), \(i) check(tree(i, depth)) + check(tree(-i, depth)))) lines <- List.append(lines, f"{iterations * 2}\t trees of depth {depth}\t check: {check_sum}\n") depth <- depth + 2 }
List.append(lines, f"long lived tree of depth {max_depth}\t check: {check(long_lived_tree)}\n")}
# ---------------------------------------------------------------------------# Driver: the same as binarytrees.R's, except that the typed program returns its lines# and the driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(12)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("binarytrees %s %.4f\n", checksum, seconds))})Binary trees, inline arithmetic binarytrees_2 1.70x
Binary trees with the child items computed inline in the recursive call and double rather than integer depths Source
execute <- function(n=9) { tree <- function(item, depth) { if (depth == 0L) return(c(item, NA, NA)) return(list(item, tree(2L * item - 1L, depth - 1L), tree(2L * item, depth - 1L))) }
check <- function(tree) if(is.na(tree[[2]][[1]])) tree[[1]] else tree[[1]] + check(tree[[2]]) - check(tree[[3]])
binarytrees_2 <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 10L
min_depth <- 4 max_depth <- max(min_depth + 2, n) stretch_depth <- max_depth + 1
cat(sep="", "stretch tree of depth ", stretch_depth, "\t check: ", check(tree(0, stretch_depth)), "\n")
long_lived_tree <- tree(0, max_depth)
for (depth in seq(min_depth, max_depth, 2)) { iterations <- as.integer(2^(max_depth - depth + min_depth)) check_sum <- sum(sapply( 1:iterations, function(i) check(tree(i, depth)) + check(tree(-i, depth)))) cat(sep="", iterations * 2L, "\t trees of depth ", depth, "\t check: ", check_sum, "\n") }
cat(sep="", "long lived tree of depth ", max_depth, "\t check: ", check(long_lived_tree), "\n") }
binarytrees_2(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(11)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("binarytrees_2 %s %.4f\n", checksum, seconds))})type Tree = :Leaf(I64) | :Node(item: I64, left: Tree, right: Tree)
tree <- function(item: I64, depth: I64) -> Tree { if (depth == 0) return(@Tree(:Leaf(item))) @Tree(:Node(item = item, left = tree(2 * item - 1, depth - 1), right = tree(2 * item, depth - 1)))}
check <- function(tree: Tree) -> I64 { match (tree) { :Leaf(item) => item :Node(item = item, left = left, right = right) => item + check(left) - check(right) }}
execute <- function(n: I64) -> List<Str> { min_depth: I64 <- 4 max_depth <- Num.max(min_depth + 2, n) stretch_depth <- max_depth + 1
lines <- [f"stretch tree of depth {stretch_depth}\t check: {check(tree(0, stretch_depth))}\n"]
long_lived_tree <- tree(0, max_depth)
depth <- min_depth while (depth <= max_depth) { iterations <- Num.pow_int(2, max_depth - depth + min_depth) check_sum <- List.sum(List.map(List.range(1, iterations), \(i) check(tree(i, depth)) + check(tree(-i, depth)))) lines <- List.append(lines, f"{iterations * 2}\t trees of depth {depth}\t check: {check_sum}\n") depth <- depth + 2 }
List.append(lines, f"long lived tree of depth {max_depth}\t check: {check(long_lived_tree)}\n")}
# ---------------------------------------------------------------------------# Driver: the same as binarytrees_2.R's, except that the typed program returns its lines# and the driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(11)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("binarytrees_2 %s %.4f\n", checksum, seconds))})Binary trees, explicit loop binarytrees_naive 1.67x
Binary trees that sums each depth's checks in a for loop instead of sapply Source
execute <- function(n=9) { tree <- function(item, depth) { if (depth == 0L) return(c(item, NA, NA)) return(list(item, tree(2L * item - 1L, depth - 1L), tree(2L * item, depth - 1L))) }
check <- function(tree) if(is.na(tree[[2]][[1]])) tree[[1]] else tree[[1]] + check(tree[[2]]) - check(tree[[3]])
binarytrees_naive <- function(args) { n = if(length(args)) as.integer(args[[1]]) else 13L
min_depth <- 4 max_depth <- max(min_depth + 2, n) stretch_depth <- max_depth + 1
cat(sep="", "stretch tree of depth ", stretch_depth, "\t check: ", check(tree(0, stretch_depth)), "\n")
long_lived_tree <- tree(0, max_depth)
for (depth in seq(min_depth, max_depth, 2)) { iterations <- as.integer(2^(max_depth - depth + min_depth)) chk_sum <- 0L for (i in 1:iterations) chk_sum <- chk_sum + check(tree(i, depth)) + check(tree(-i, depth)) cat(sep="", iterations * 2L, "\t trees of depth ", depth, "\t check ", chk_sum, "\n") }
cat(sep="", "long lived tree of depth ", max_depth, "\t check: ", check(long_lived_tree), "\n") }
binarytrees_naive(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(12)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("binarytrees_naive %s %.4f\n", checksum, seconds))})type Tree = :Leaf(I64) | :Node(item: I64, left: Tree, right: Tree)
tree <- function(item: I64, depth: I64) -> Tree { if (depth == 0) return(@Tree(:Leaf(item))) @Tree(:Node(item = item, left = tree(2 * item - 1, depth - 1), right = tree(2 * item, depth - 1)))}
check <- function(tree: Tree) -> I64 { match (tree) { :Leaf(item) => item :Node(item = item, left = left, right = right) => item + check(left) - check(right) }}
execute <- function(n: I64) -> List<Str> { min_depth: I64 <- 4 max_depth <- Num.max(min_depth + 2, n) stretch_depth <- max_depth + 1
lines <- [f"stretch tree of depth {stretch_depth}\t check: {check(tree(0, stretch_depth))}\n"]
long_lived_tree <- tree(0, max_depth)
depth <- min_depth while (depth <= max_depth) { iterations <- Num.pow_int(2, max_depth - depth + min_depth) check_sum <- 0 for (i in List.range(1, iterations)) check_sum <- check_sum + check(tree(i, depth)) + check(tree(-i, depth)) lines <- List.append(lines, f"{iterations * 2}\t trees of depth {depth}\t check {check_sum}\n") depth <- depth + 2 }
List.append(lines, f"long lived tree of depth {max_depth}\t check: {check(long_lived_tree)}\n")}
# ---------------------------------------------------------------------------# Driver: the same as binarytrees_naive.R's, except that the typed program returns its lines# and the driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(12)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("binarytrees_naive %s %.4f\n", checksum, seconds))})Fannkuch-redux fannkuchredux 1.66x
Counts pancake flips over all permutations of 9 elements, reversing prefixes with vectorized rev and slice assignment Source
execute <- function(n=9) { fannkuch <- function(n) { one_two = c(1, 2) two_one = c(2, 1) two_three = c(2, 3) three_two = c(3, 2) if (n > 3L) rxrange = 3:(n - 1) else rxrange = integer(0)
max_flip_count <- 0L perm_sign <- TRUE checksum <- 0L perm1 <- 1:n count <- 0:(n - 1L) while (TRUE) { if (k <- perm1[[1L]]) { perm <- perm1 flip_count <- 1L while ((kk <- perm[[k]]) > 1L) { k_range <- 1:k perm[k_range] <- rev.default(perm[k_range]) flip_count <- flip_count + 1L k <- kk kk <- perm[[kk]] } max_flip_count <- max(max_flip_count, flip_count) checksum <- checksum + if (perm_sign) flip_count else -flip_count }
# Use incremental change to generate another permutation if (perm_sign) { perm1[one_two] <- perm1[two_one] perm_sign <- FALSE } else { perm1[two_three] <- perm1[three_two] perm_sign = TRUE was_break <- FALSE for (r in rxrange) { if (count[[r]]) { was_break <- TRUE break } count[[r]] <- r - 1L perm0 <- perm1[[1L]] perm1[1:r] <- perm1[2:(r + 1L)] perm1[[r + 1L]] <- perm0 } if (!was_break) { r <- n if (!count[[r]]) { cat(checksum, "\n", sep="") return(max_flip_count) } } count[[r]] <- count[[r]] - 1L } } }
fannkuchredux <- function(args) { n <- if (length(args)) as.integer(args[[1]]) else 12L fannkuch(n) }
fannkuchredux(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(9)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fannkuchredux %s %.4f\n", checksum, seconds))})fannkuch <- function(n: I64) -> Record{checksum: I64, max_flips: I64} { max_flips: I64 <- 0 checksum: I64 <- 0 sign <- Bool.true perm1 <- List.range(1, n) count <- List.range(0, n - 1) while (Bool.true) { k <- perm1[[1]] perm <- perm1 flips: I64 <- 1 kk <- perm[[k]] while (kk > 1) { perm <- List.concat(List.reverse(List.take_first(perm, k)), List.drop_first(perm, k)) flips <- flips + 1 k <- kk kk <- perm[[k]] } max_flips <- Num.max(max_flips, flips) checksum <- if (sign) checksum + flips else checksum - flips
# The next permutation, by incremental change. if (sign) { perm1 <- List.swap(perm1, 1, 2) sign <- Bool.false } else { perm1 <- List.swap(perm1, 2, 3) sign <- Bool.true r <- 3 found <- Bool.false while (!found && r <= n - 1) { if (count[[r]] != 0) { found <- Bool.true } else { count[[r]] <- r - 1 perm0 <- perm1[[1]] perm1 <- List.concat(List.append(List.sublist(perm1, 2, r), perm0), List.drop_first(perm1, r + 1)) r <- r + 1 } } if (!found) { r <- n if (count[[r]] == 0) return((checksum = checksum, max_flips = max_flips)) } count[[r]] <- count[[r]] - 1 } } (checksum = checksum, max_flips = max_flips)}
# ---------------------------------------------------------------------------# Driver: the same as fannkuchredux.R's, except that the typed program returns the# checksum it prints and the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output({ result <- fannkuch(9) cat(Num.to_r(result$checksum), "\n", sep = "") }) seconds <- proc.time()[[3]] - started value <- Num.to_r(result$max_flips) text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fannkuchredux %s %.4f\n", checksum, seconds))})Fannkuch-redux, scalar swaps fannkuchredux_naive 4.37x
Fannkuch-redux that reverses prefixes and rotates the permutation one element at a time with [[ swaps Source
execute <- function(n=9) { fannkuch <- function(n) { if (n > 3L) rxrange = 3:(n - 1) else rxrange = integer(0)
max_flip_count <- 0L perm_sign <- TRUE checksum <- 0L perm1 <- 1:n count <- 0:(n - 1L) while (TRUE) { if (k <- perm1[[1L]]) { perm <- perm1 flip_count <- 1L while ((kk <- perm[[k]]) > 1L) { for (lo in 1:(k %/% 2L)) { hi = k - lo + 1L t <- perm[[lo]]; perm[[lo]] <- perm[[hi]]; perm[[hi]] <- t } flip_count <- flip_count + 1L k <- kk kk <- perm[[kk]] } max_flip_count <- max(max_flip_count, flip_count) checksum <- checksum + if (perm_sign) flip_count else -flip_count }
# Use incremental change to generate another permutation if (perm_sign) { t <- perm1[[1]]; perm1[[1]] <- perm1[[2]]; perm1[[2]] <- t perm_sign = FALSE } else { t <- perm1[[2]]; perm1[[2]] <- perm1[[3]]; perm1[[3]] <- t perm_sign = TRUE was_break <- FALSE for (r in rxrange) { if (count[[r]]) { was_break <- TRUE break } count[[r]] <- r - 1L perm0 <- perm1[[1L]] for (i in 1:r) perm1[[i]] <- perm1[[i + 1L]] perm1[[r + 1L]] <- perm0 } if (!was_break) { r <- n if (!count[[r]]) { cat(checksum, "\n", sep="") return(max_flip_count) } } count[[r]] <- count[[r]] - 1L } } }
fannkuchredux_naive <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 12L fannkuch(n) }
fannkuchredux_naive(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(9)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fannkuchredux_naive %s %.4f\n", checksum, seconds))})fannkuch <- function(n: I64) -> Record{checksum: I64, max_flips: I64} { max_flips: I64 <- 0 checksum: I64 <- 0 sign <- Bool.true perm1 <- List.range(1, n) count <- List.range(0, n - 1) while (Bool.true) { k <- perm1[[1]] perm <- perm1 flips: I64 <- 1 kk <- perm[[k]] while (kk > 1) { for (lo in List.range(1, k %/% 2)) perm <- List.swap(perm, lo, k - lo + 1) flips <- flips + 1 k <- kk kk <- perm[[k]] } max_flips <- Num.max(max_flips, flips) checksum <- if (sign) checksum + flips else checksum - flips
# The next permutation, by incremental change. if (sign) { perm1 <- List.swap(perm1, 1, 2) sign <- Bool.false } else { perm1 <- List.swap(perm1, 2, 3) sign <- Bool.true r <- 3 found <- Bool.false while (!found && r <= n - 1) { if (count[[r]] != 0) { found <- Bool.true } else { count[[r]] <- r - 1 perm0 <- perm1[[1]] for (i in List.range(1, r)) perm1[[i]] <- perm1[[i + 1]] perm1[[r + 1]] <- perm0 r <- r + 1 } } if (!found) { r <- n if (count[[r]] == 0) return((checksum = checksum, max_flips = max_flips)) } count[[r]] <- count[[r]] - 1 } } (checksum = checksum, max_flips = max_flips)}
# ---------------------------------------------------------------------------# Driver: the same as fannkuchredux_naive.R's, except that the typed program returns the# checksum it prints and the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output({ result <- fannkuch(9) cat(Num.to_r(result$checksum), "\n", sep = "") }) seconds <- proc.time()[[3]] - started value <- Num.to_r(result$max_flips) text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fannkuchredux_naive %s %.4f\n", checksum, seconds))})Fasta fasta 3.43x
Generates DNA sequences with an integer LCG, picking each line's codes at once with outer() and colSums Source
execute <- function(n=60000) { width <- 60L myrandom_last <- 42L myrandom <- function(m) { myrandom_last <<- (myrandom_last * 3877L + 29573L) %% 139968L return(m * myrandom_last / 139968) }
alu <- paste( "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA", sep="", collapse="")
iub <- matrix(c( c(0.27, 'a'), c(0.12, 'c'), c(0.12, 'g'), c(0.27, 't'), c(0.02, 'B'), c(0.02, 'D'), c(0.02, 'H'), c(0.02, 'K'), c(0.02, 'M'), c(0.02, 'N'), c(0.02, 'R'), c(0.02, 'S'), c(0.02, 'V'), c(0.02, 'W'), c(0.02, 'Y') ), 2)
homosapiens <- matrix(c( c(0.3029549426680, 'a'), c(0.1979883004921, 'c'), c(0.1975473066391, 'g'), c(0.3015094502008, 't') ), 2)
repeat_fasta <- function(s, count) { chars <- strsplit(s, split="")[[1]] len <- nchar(s) s2 <- c(chars, chars[1:width]) pos <- 1L while (count) { line <- min(width, count) next_pos <- pos + line cat(s2[pos:(next_pos - 1)], "\n", sep="") pos <- next_pos if (pos > len) pos <- pos - len count <- count - line } }
random_fasta <- function(genelist, count) { psum <- cumsum(genelist[1,]) while (count) { line <- min(width, count)
rs <- double(line) for (i in 1:line) rs[[i]] <- myrandom(1)
cat(genelist[2, colSums(outer(psum, rs, "<")) + 1], "\n", sep='') count <- count - line } }
fasta <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 1000L cat(">ONE Homo sapiens alu\n") repeat_fasta(alu, 2 * n) cat(">TWO IUB ambiguity codes\n") random_fasta(iub, 3L * n) cat(">THREE Homo sapiens frequency\n") random_fasta(homosapiens, 5L * n) }
fasta(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(60000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fasta %s %.4f\n", checksum, seconds))})alias Gene = Record{probability: F64, code: I64}
execute <- function(n: I64) -> List<Str> { alu <- Str.join_with([ "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA" ], "")
iub <- genes([ (0.27f64, "a"), (0.12f64, "c"), (0.12f64, "g"), (0.27f64, "t"), (0.02f64, "B"), (0.02f64, "D"), (0.02f64, "H"), (0.02f64, "K"), (0.02f64, "M"), (0.02f64, "N"), (0.02f64, "R"), (0.02f64, "S"), (0.02f64, "V"), (0.02f64, "W"), (0.02f64, "Y") ]) homosapiens <- genes([ (0.3029549426680f64, "a"), (0.1979883004921f64, "c"), (0.1975473066391f64, "g"), (0.3015094502008f64, "t") ])
lines <- List.append(repeat_fasta([">ONE Homo sapiens alu\n"], alu, 2 * n), ">TWO IUB ambiguity codes\n") two <- random_fasta(lines, iub, 3 * n, 42) three <- random_fasta(List.append(two$lines, ">THREE Homo sapiens frequency\n"), homosapiens, 5 * n, two$seed) three$lines}
# The cumulative probabilities, each with its code as a byte.genes <- function(table: List<Tuple{F64, Str}>) -> List<Gene> { total: F64 <- 0 genes <- [] for (entry in table) { total <- total + entry[[1]] genes <- List.append(genes, (probability = total, code = Str.to_utf8(entry[[2]])[[1]])) } genes}
repeat_fasta <- function(lines: List<Str>, s: Str, count: I64) -> List<Str> { width <- 60 chars <- Str.to_utf8(s) len <- List.len(chars) doubled <- List.concat(chars, List.take_first(chars, width)) pos <- 1 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(List.sublist(doubled, pos, line)), "\n")) pos <- pos + line if (pos > len) pos <- pos - len remaining <- remaining - line } lines}
random_fasta <- function(lines: List<Str>, genes: List<Gene>, count: I64, seed: I64) -> Record{lines: List<Str>, seed: I64} { width <- 60 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) bytes <- [] for (i in List.range(1, line)) { seed <- (seed * 3877 + 29573) %% 139968 r <- Num.to_f64(seed) / 139968 bytes <- List.append(bytes, genes[[List.count_if(genes, \(gene) gene$probability < r) + 1]]$code) } lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(bytes), "\n")) remaining <- remaining - line } (lines = lines, seed = seed)}
# ---------------------------------------------------------------------------# Driver: the same as fasta.R's, except that the typed program returns its lines and the# driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(60000)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fasta %s %.4f\n", checksum, seconds))})Fasta, vectorized linear search fasta_2 3.86x
Fasta that picks each line's codes by a vectorized linear search, advancing indices with which() until all match Source
execute <- function(n=60000) { width <- 60L myrandom_last <- 42L myrandom <- function(m) { myrandom_last <<- (myrandom_last * 3877L + 29573L) %% 139968L return(m * myrandom_last / 139968) }
alu <- paste( "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA", sep="", collapse="")
iub <- matrix(c( c(0.27, 'a'), c(0.12, 'c'), c(0.12, 'g'), c(0.27, 't'), c(0.02, 'B'), c(0.02, 'D'), c(0.02, 'H'), c(0.02, 'K'), c(0.02, 'M'), c(0.02, 'N'), c(0.02, 'R'), c(0.02, 'S'), c(0.02, 'V'), c(0.02, 'W'), c(0.02, 'Y') ), 2)
homosapiens <- matrix(c( c(0.3029549426680, 'a'), c(0.1979883004921, 'c'), c(0.1975473066391, 'g'), c(0.3015094502008, 't') ), 2)
repeat_fasta <- function(s, count) { chars <- strsplit(s, split="")[[1]] len <- nchar(s) s2 <- c(chars, chars[1:width]) pos <- 1L while (count) { line <- min(width, count) next_pos <- pos + line cat(s2[pos:(next_pos - 1)], "\n", sep="") pos <- next_pos if (pos > len) pos <- pos - len count <- count - line } }
random_fasta <- function(genelist, count) { psum = cumsum(genelist[1,]) n = length(psum) while (count) { line = min(width, count) rs <- double(line) for (i in 1:line) rs[[i]] <- myrandom(1)
# Linear search (vectorized) inds <- 1:line lo <- rep.int(1L, line) while (length(inds <- which(psum[lo] < rs))) lo[inds] <- lo[inds] + 1L
cat(genelist[2, lo], "\n", sep='') count <- count - line } }
fasta_2 <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 1000L cat(">ONE Homo sapiens alu\n") repeat_fasta(alu, 2 * n) cat(">TWO IUB ambiguity codes\n") random_fasta(iub, 3L * n) cat(">THREE Homo sapiens frequency\n") random_fasta(homosapiens, 5L * n) }
fasta_2(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(60000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fasta_2 %s %.4f\n", checksum, seconds))})alias Gene = Record{probability: F64, code: I64}
execute <- function(n: I64) -> List<Str> { alu <- Str.join_with([ "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA" ], "")
iub <- genes([ (0.27f64, "a"), (0.12f64, "c"), (0.12f64, "g"), (0.27f64, "t"), (0.02f64, "B"), (0.02f64, "D"), (0.02f64, "H"), (0.02f64, "K"), (0.02f64, "M"), (0.02f64, "N"), (0.02f64, "R"), (0.02f64, "S"), (0.02f64, "V"), (0.02f64, "W"), (0.02f64, "Y") ]) homosapiens <- genes([ (0.3029549426680f64, "a"), (0.1979883004921f64, "c"), (0.1975473066391f64, "g"), (0.3015094502008f64, "t") ])
lines <- List.append(repeat_fasta([">ONE Homo sapiens alu\n"], alu, 2 * n), ">TWO IUB ambiguity codes\n") two <- random_fasta(lines, iub, 3 * n, 42) three <- random_fasta(List.append(two$lines, ">THREE Homo sapiens frequency\n"), homosapiens, 5 * n, two$seed) three$lines}
# The cumulative probabilities, each with its code as a byte.genes <- function(table: List<Tuple{F64, Str}>) -> List<Gene> { total: F64 <- 0 genes <- [] for (entry in table) { total <- total + entry[[1]] genes <- List.append(genes, (probability = total, code = Str.to_utf8(entry[[2]])[[1]])) } genes}
repeat_fasta <- function(lines: List<Str>, s: Str, count: I64) -> List<Str> { width <- 60 chars <- Str.to_utf8(s) len <- List.len(chars) doubled <- List.concat(chars, List.take_first(chars, width)) pos <- 1 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(List.sublist(doubled, pos, line)), "\n")) pos <- pos + line if (pos > len) pos <- pos - len remaining <- remaining - line } lines}
random_fasta <- function(lines: List<Str>, genes: List<Gene>, count: I64, seed: I64) -> Record{lines: List<Str>, seed: I64} { width <- 60 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) rs <- List.repeat(0, line) for (i in List.range(1, line)) { seed <- (seed * 3877 + 29573) %% 139968 rs[[i]] <- Num.to_f64(seed) / 139968 }
# Linear search, advancing every unfinished search by one gene per pass. lo <- List.repeat(1, line) inds <- below(genes, lo, rs) while (!List.is_empty(inds)) { for (i in inds) lo[[i]] <- lo[[i]] + 1 inds <- below(genes, lo, rs) } bytes <- List.map(lo, \(index) genes[[index]]$code) lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(bytes), "\n")) remaining <- remaining - line } (lines = lines, seed = seed)}
# The positions whose search has not yet reached a gene at or above its random number.below <- function(genes: List<Gene>, lo: List<I64>, rs: List<F64>) -> List<I64> { List.keep_if(List.range(1, List.len(rs)), \(i) genes[[lo[[i]]]]$probability < rs[[i]])}
# ---------------------------------------------------------------------------# Driver: the same as fasta_2.R's, except that the typed program returns its lines and the# driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(60000)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fasta_2 %s %.4f\n", checksum, seconds))})Fasta, vectorized binary search fasta_3 3.93x
Fasta that picks each line's codes by a vectorized binary search over the cumulative probabilities Source
execute <- function(n=60000) { width <- 60L myrandom_last <- 42L myrandom <- function(m) { myrandom_last <<- (myrandom_last * 3877L + 29573L) %% 139968L return(m * myrandom_last / 139968) }
alu <- paste( "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA", sep="", collapse="")
iub <- matrix(c( c(0.27, 'a'), c(0.12, 'c'), c(0.12, 'g'), c(0.27, 't'), c(0.02, 'B'), c(0.02, 'D'), c(0.02, 'H'), c(0.02, 'K'), c(0.02, 'M'), c(0.02, 'N'), c(0.02, 'R'), c(0.02, 'S'), c(0.02, 'V'), c(0.02, 'W'), c(0.02, 'Y') ), 2)
homosapiens <- matrix(c( c(0.3029549426680, 'a'), c(0.1979883004921, 'c'), c(0.1975473066391, 'g'), c(0.3015094502008, 't') ), 2)
repeat_fasta <- function(s, count) { chars <- strsplit(s, split="")[[1]] len <- nchar(s) s2 <- c(chars, chars[1:width]) pos <- 1L while (count) { line <- min(width, count) next_pos <- pos + line cat(s2[pos:(next_pos - 1)], "\n", sep="") pos <- next_pos if (pos > len) pos <- pos - len count <- count - line } }
random_fasta <- function(genelist, count) { psum = cumsum(genelist[1,]) n = length(psum) while (count) { line = min(width, count) rs <- double(line) for (i in 1:line) rs[[i]] <- myrandom(1)
# Binary search (vectorized) inds <- 1:line lo <- rep.int(1L, line); hi <- rep.int(n, line) mid <- integer(line) repeat { mid[inds] <- (lo[inds] + hi[inds] - 1L) %/% 2 ge_inds = which(psum[mid] >= rs) hi[ge_inds] <- mid[ge_inds] lt_inds = which(psum[mid] < rs) lo[lt_inds] <- mid[lt_inds] + 1L inds <- which(lo < hi) if (!length(inds)) break }
cat(genelist[2, hi], "\n", sep='') count <- count - line } }
fasta_3 <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 1000L cat(">ONE Homo sapiens alu\n") repeat_fasta(alu, 2 * n) cat(">TWO IUB ambiguity codes\n") random_fasta(iub, 3L * n) cat(">THREE Homo sapiens frequency\n") random_fasta(homosapiens, 5L * n) }
fasta_3(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(60000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fasta_3 %s %.4f\n", checksum, seconds))})alias Gene = Record{probability: F64, code: I64}
execute <- function(n: I64) -> List<Str> { alu <- Str.join_with([ "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA" ], "")
iub <- genes([ (0.27f64, "a"), (0.12f64, "c"), (0.12f64, "g"), (0.27f64, "t"), (0.02f64, "B"), (0.02f64, "D"), (0.02f64, "H"), (0.02f64, "K"), (0.02f64, "M"), (0.02f64, "N"), (0.02f64, "R"), (0.02f64, "S"), (0.02f64, "V"), (0.02f64, "W"), (0.02f64, "Y") ]) homosapiens <- genes([ (0.3029549426680f64, "a"), (0.1979883004921f64, "c"), (0.1975473066391f64, "g"), (0.3015094502008f64, "t") ])
lines <- List.append(repeat_fasta([">ONE Homo sapiens alu\n"], alu, 2 * n), ">TWO IUB ambiguity codes\n") two <- random_fasta(lines, iub, 3 * n, 42) three <- random_fasta(List.append(two$lines, ">THREE Homo sapiens frequency\n"), homosapiens, 5 * n, two$seed) three$lines}
# The cumulative probabilities, each with its code as a byte.genes <- function(table: List<Tuple{F64, Str}>) -> List<Gene> { total: F64 <- 0 genes <- [] for (entry in table) { total <- total + entry[[1]] genes <- List.append(genes, (probability = total, code = Str.to_utf8(entry[[2]])[[1]])) } genes}
repeat_fasta <- function(lines: List<Str>, s: Str, count: I64) -> List<Str> { width <- 60 chars <- Str.to_utf8(s) len <- List.len(chars) doubled <- List.concat(chars, List.take_first(chars, width)) pos <- 1 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(List.sublist(doubled, pos, line)), "\n")) pos <- pos + line if (pos > len) pos <- pos - len remaining <- remaining - line } lines}
random_fasta <- function(lines: List<Str>, genes: List<Gene>, count: I64, seed: I64) -> Record{lines: List<Str>, seed: I64} { width <- 60 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) rs <- List.repeat(0, line) for (i in List.range(1, line)) { seed <- (seed * 3877 + 29573) %% 139968 rs[[i]] <- Num.to_f64(seed) / 139968 }
# Binary search, halving every unfinished search per pass. n <- List.len(genes) lo <- List.repeat(1, line) hi <- List.repeat(n, line) mid <- List.repeat(0, line) inds <- List.range(1, line) while (!List.is_empty(inds)) { for (i in inds) mid[[i]] <- (lo[[i]] + hi[[i]] - 1) %/% 2 below <- List.map2(mid, rs, \(m, r) genes[[m]]$probability < r) hi <- List.map3(hi, mid, below, \(h, m, b) if (b) h else m) lo <- List.map3(lo, mid, below, \(l, m, b) if (b) m + 1 else l) inds <- List.keep_if(List.range(1, line), \(i) lo[[i]] < hi[[i]]) } bytes <- List.map(hi, \(index) genes[[index]]$code) lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(bytes), "\n")) remaining <- remaining - line } (lines = lines, seed = seed)}
# ---------------------------------------------------------------------------# Driver: the same as fasta_3.R's, except that the typed program returns its lines and the# driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(60000)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fasta_3 %s %.4f\n", checksum, seconds))})Fasta, scalar linear search fasta_naive 4.53x
Fasta that picks each character with a scalar linear search loop and joins every line with paste Source
execute <- function(n=80000) { width <- 60L myrandom_last <- 42L myrandom <- function(m) { myrandom_last <<- (myrandom_last * 3877L + 29573L) %% 139968L return(m * myrandom_last / 139968) }
alu <- paste( "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA", sep="", collapse="")
iub <- matrix(c( c(0.27, 'a'), c(0.12, 'c'), c(0.12, 'g'), c(0.27, 't'), c(0.02, 'B'), c(0.02, 'D'), c(0.02, 'H'), c(0.02, 'K'), c(0.02, 'M'), c(0.02, 'N'), c(0.02, 'R'), c(0.02, 'S'), c(0.02, 'V'), c(0.02, 'W'), c(0.02, 'Y') ), 2)
homosapiens <- matrix(c( c(0.3029549426680, 'a'), c(0.1979883004921, 'c'), c(0.1975473066391, 'g'), c(0.3015094502008, 't') ), 2)
repeat_fasta <- function(s, count) { chars = strsplit(s, split="")[[1]] len = nchar(s) s2 <- character(len + width) for (i in 1:len) s2[[i]] <- chars[[i]] for (i in 1:width) s2[[len + i]] <- chars[[i]] pos <- 1L while (count) { line = min(width, count) next_pos <- pos + line cat(paste(s2[pos:(next_pos - 1)], collapse="", sep=""), "\n", sep="") pos <- next_pos if (pos > len) pos <- pos - len count <- count - line } }
random_fasta <- function(genelist, count) { psum = cumsum(genelist[1,]) n = length(psum) while (count) { line = min(width, count) seq <- character(line) for (i in 1:line) { r <- myrandom(1) lo <- 1L while (psum[[lo]] < r) lo <- lo + 1L seq[[i]] <- genelist[[2, lo]] } cat(paste(seq, collapse="", sep=""), "\n", sep='') count <- count - line } }
fasta_naive <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 1000L cat(">ONE Homo sapiens alu\n") repeat_fasta(alu, 2 * n) cat(">TWO IUB ambiguity codes\n") random_fasta(iub, 3L * n) cat(">THREE Homo sapiens frequency\n") random_fasta(homosapiens, 5L * n) }
fasta_naive(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(80000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fasta_naive %s %.4f\n", checksum, seconds))})alias Gene = Record{probability: F64, code: I64}
execute <- function(n: I64) -> List<Str> { alu <- Str.join_with([ "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA" ], "")
iub <- genes([ (0.27f64, "a"), (0.12f64, "c"), (0.12f64, "g"), (0.27f64, "t"), (0.02f64, "B"), (0.02f64, "D"), (0.02f64, "H"), (0.02f64, "K"), (0.02f64, "M"), (0.02f64, "N"), (0.02f64, "R"), (0.02f64, "S"), (0.02f64, "V"), (0.02f64, "W"), (0.02f64, "Y") ]) homosapiens <- genes([ (0.3029549426680f64, "a"), (0.1979883004921f64, "c"), (0.1975473066391f64, "g"), (0.3015094502008f64, "t") ])
lines <- List.append(repeat_fasta([">ONE Homo sapiens alu\n"], alu, 2 * n), ">TWO IUB ambiguity codes\n") two <- random_fasta(lines, iub, 3 * n, 42) three <- random_fasta(List.append(two$lines, ">THREE Homo sapiens frequency\n"), homosapiens, 5 * n, two$seed) three$lines}
# The cumulative probabilities, each with its code as a byte.genes <- function(table: List<Tuple{F64, Str}>) -> List<Gene> { total: F64 <- 0 genes <- [] for (entry in table) { total <- total + entry[[1]] genes <- List.append(genes, (probability = total, code = Str.to_utf8(entry[[2]])[[1]])) } genes}
repeat_fasta <- function(lines: List<Str>, s: Str, count: I64) -> List<Str> { width <- 60 chars <- Str.to_utf8(s) len <- List.len(chars) doubled <- List.repeat(0, len + width) for (i in List.range(1, len)) doubled[[i]] <- chars[[i]] for (i in List.range(1, width)) doubled[[len + i]] <- chars[[i]] pos <- 1 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(List.sublist(doubled, pos, line)), "\n")) pos <- pos + line if (pos > len) pos <- pos - len remaining <- remaining - line } lines}
random_fasta <- function(lines: List<Str>, genes: List<Gene>, count: I64, seed: I64) -> Record{lines: List<Str>, seed: I64} { width <- 60 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) bytes <- List.repeat(0, line) for (i in List.range(1, line)) { seed <- (seed * 3877 + 29573) %% 139968 r <- Num.to_f64(seed) / 139968 lo <- 1 while (genes[[lo]]$probability < r) lo <- lo + 1 bytes[[i]] <- genes[[lo]]$code } lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(bytes), "\n")) remaining <- remaining - line } (lines = lines, seed = seed)}
# ---------------------------------------------------------------------------# Driver: the same as fasta_naive.R's, except that the typed program returns its lines and the# driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(80000)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fasta_naive %s %.4f\n", checksum, seconds))})Fasta, scalar binary search fasta_naive_2 3.40x
Fasta that picks each character with a scalar binary search loop and joins every line with paste Source
execute <- function(n=80000) { width <- 60L myrandom_last <- 42L myrandom <- function(m) { myrandom_last <<- (myrandom_last * 3877L + 29573L) %% 139968L return(m * myrandom_last / 139968) }
alu <- paste( "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA", sep="", collapse="")
iub <- matrix(c( c(0.27, 'a'), c(0.12, 'c'), c(0.12, 'g'), c(0.27, 't'), c(0.02, 'B'), c(0.02, 'D'), c(0.02, 'H'), c(0.02, 'K'), c(0.02, 'M'), c(0.02, 'N'), c(0.02, 'R'), c(0.02, 'S'), c(0.02, 'V'), c(0.02, 'W'), c(0.02, 'Y') ), 2)
homosapiens <- matrix(c( c(0.3029549426680, 'a'), c(0.1979883004921, 'c'), c(0.1975473066391, 'g'), c(0.3015094502008, 't') ), 2)
repeat_fasta <- function(s, count) { chars = strsplit(s, split="")[[1]] len = nchar(s) s2 <- character(len + width) for (i in 1:len) s2[[i]] <- chars[[i]] for (i in 1:width) s2[[len + i]] <- chars[[i]] pos <- 1L while (count) { line = min(width, count) next_pos <- pos + line cat(paste(s2[pos:(next_pos - 1)], collapse="", sep=""), "\n", sep="") pos <- next_pos if (pos > len) pos <- pos - len count <- count - line } }
random_fasta <- function(genelist, count) { psum = cumsum(genelist[1,]) n = length(psum) while (count) { line = min(width, count) seq <- character(line) for (i in 1:line) { r <- myrandom(1) # Binary search lo <- 1L; hi <- n while (lo < hi) { mid <- (lo + hi - 1L) %/% 2 if (psum[[mid]] >= r) hi <- mid else lo <- mid + 1L } seq[[i]] <- genelist[[2, hi]] } cat(paste(seq, collapse="", sep=""), "\n", sep='') count <- count - line } }
fasta_naive_2 <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 1000L cat(">ONE Homo sapiens alu\n") repeat_fasta(alu, 2 * n) cat(">TWO IUB ambiguity codes\n") random_fasta(iub, 3L * n) cat(">THREE Homo sapiens frequency\n") random_fasta(homosapiens, 5L * n) }
fasta_naive_2(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(80000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fasta_naive_2 %s %.4f\n", checksum, seconds))})alias Gene = Record{probability: F64, code: I64}
execute <- function(n: I64) -> List<Str> { alu <- Str.join_with([ "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA" ], "")
iub <- genes([ (0.27f64, "a"), (0.12f64, "c"), (0.12f64, "g"), (0.27f64, "t"), (0.02f64, "B"), (0.02f64, "D"), (0.02f64, "H"), (0.02f64, "K"), (0.02f64, "M"), (0.02f64, "N"), (0.02f64, "R"), (0.02f64, "S"), (0.02f64, "V"), (0.02f64, "W"), (0.02f64, "Y") ]) homosapiens <- genes([ (0.3029549426680f64, "a"), (0.1979883004921f64, "c"), (0.1975473066391f64, "g"), (0.3015094502008f64, "t") ])
lines <- List.append(repeat_fasta([">ONE Homo sapiens alu\n"], alu, 2 * n), ">TWO IUB ambiguity codes\n") two <- random_fasta(lines, iub, 3 * n, 42) three <- random_fasta(List.append(two$lines, ">THREE Homo sapiens frequency\n"), homosapiens, 5 * n, two$seed) three$lines}
# The cumulative probabilities, each with its code as a byte.genes <- function(table: List<Tuple{F64, Str}>) -> List<Gene> { total: F64 <- 0 genes <- [] for (entry in table) { total <- total + entry[[1]] genes <- List.append(genes, (probability = total, code = Str.to_utf8(entry[[2]])[[1]])) } genes}
repeat_fasta <- function(lines: List<Str>, s: Str, count: I64) -> List<Str> { width <- 60 chars <- Str.to_utf8(s) len <- List.len(chars) doubled <- List.repeat(0, len + width) for (i in List.range(1, len)) doubled[[i]] <- chars[[i]] for (i in List.range(1, width)) doubled[[len + i]] <- chars[[i]] pos <- 1 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(List.sublist(doubled, pos, line)), "\n")) pos <- pos + line if (pos > len) pos <- pos - len remaining <- remaining - line } lines}
random_fasta <- function(lines: List<Str>, genes: List<Gene>, count: I64, seed: I64) -> Record{lines: List<Str>, seed: I64} { width <- 60 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) bytes <- List.repeat(0, line) for (i in List.range(1, line)) { seed <- (seed * 3877 + 29573) %% 139968 r <- Num.to_f64(seed) / 139968 lo <- 1 hi <- List.len(genes) while (lo < hi) { mid <- (lo + hi - 1) %/% 2 if (genes[[mid]]$probability >= r) hi <- mid else lo <- mid + 1 } bytes[[i]] <- genes[[hi]]$code } lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(bytes), "\n")) remaining <- remaining - line } (lines = lines, seed = seed)}
# ---------------------------------------------------------------------------# Driver: the same as fasta_naive_2.R's, except that the typed program returns its lines and the# driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(80000)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fasta_naive_2 %s %.4f\n", checksum, seconds))})Fasta-redux fastaredux 4.72x
Fasta with a 4,096-entry lookup table that maps a random number to a code, corrected for a whole line at a time Source
execute <- function(n=80000) { width = 60L lookup_size = 4096L lookup_scale = as.double(lookup_size - 1L)
alu = paste( "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA", sep="", collapse="")
iub = matrix(c( c(0.27, 'a'), c(0.12, 'c'), c(0.12, 'g'), c(0.27, 't'), c(0.02, 'B'), c(0.02, 'D'), c(0.02, 'H'), c(0.02, 'K'), c(0.02, 'M'), c(0.02, 'N'), c(0.02, 'R'), c(0.02, 'S'), c(0.02, 'V'), c(0.02, 'W'), c(0.02, 'Y') ), 2)
homosapiens = matrix(c( c(0.3029549426680, 'a'), c(0.1979883004921, 'c'), c(0.1975473066391, 'g'), c(0.3015094502008, 't') ), 2)
random <- 42L random_next_lookup <- function() { random <<- (random * 3877L + 29573L) %% 139968L return(random * (lookup_scale / 139968)) # TODO }
repeat_fasta <- function(s, count) { chars = strsplit(s, split="")[[1]] len = nchar(s) s2 = c(chars, chars[1:width]) pos <- 1L while (count) { line = min(width, count) next_pos <- pos + line cat(s2[pos:(next_pos - 1)], "\n", sep="") pos <- next_pos if (pos > len) pos <- pos - len count <- count - line } }
random_fasta <- function(genelist, count) { n = ncol(genelist) lookup <- integer(lookup_size) cprob_lookup <- cumsum(genelist[1, ]) * lookup_scale cprob_lookup[[n]] <- lookup_size - 1
j <- 1L for (i in 1:lookup_size) { while (cprob_lookup[[j]] + 1L < i) j <- j + 1L lookup[[i]] <- j }
while (count) { line <- min(width, count)
rs <- double(line) for (i in 1:line) rs[[i]] <- random_next_lookup()
inds <- lookup[rs + 1L] missed <- which(cprob_lookup[inds] < rs) if (length(missed)) repeat { inds[missed] <- inds[missed] + 1L missed <- which(cprob_lookup[inds] < rs) if (!length(missed)) break }
cat(paste(genelist[2, inds], collapse="", sep=""), "\n", sep="") count <- count - line }
}
fastaredux <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 1000L cat(">ONE Homo sapiens alu\n") repeat_fasta(alu, 2 * n) cat(">TWO IUB ambiguity codes\n") random_fasta(iub, 3L * n) cat(">THREE Homo sapiens frequency\n") random_fasta(homosapiens, 5L * n) }
fastaredux(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(80000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fastaredux %s %.4f\n", checksum, seconds))})alias Gene = Record{probability: F64, code: I64}
execute <- function(n: I64) -> List<Str> { alu <- Str.join_with([ "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA" ], "")
iub <- genes([ (0.27f64, "a"), (0.12f64, "c"), (0.12f64, "g"), (0.27f64, "t"), (0.02f64, "B"), (0.02f64, "D"), (0.02f64, "H"), (0.02f64, "K"), (0.02f64, "M"), (0.02f64, "N"), (0.02f64, "R"), (0.02f64, "S"), (0.02f64, "V"), (0.02f64, "W"), (0.02f64, "Y") ]) homosapiens <- genes([ (0.3029549426680f64, "a"), (0.1979883004921f64, "c"), (0.1975473066391f64, "g"), (0.3015094502008f64, "t") ])
lines <- List.append(repeat_fasta([">ONE Homo sapiens alu\n"], alu, 2 * n), ">TWO IUB ambiguity codes\n") two <- random_fasta(lines, iub, 3 * n, 42) three <- random_fasta(List.append(two$lines, ">THREE Homo sapiens frequency\n"), homosapiens, 5 * n, two$seed) three$lines}
# The cumulative probabilities, each with its code as a byte.genes <- function(table: List<Tuple{F64, Str}>) -> List<Gene> { total: F64 <- 0 genes <- [] for (entry in table) { total <- total + entry[[1]] genes <- List.append(genes, (probability = total, code = Str.to_utf8(entry[[2]])[[1]])) } genes}
repeat_fasta <- function(lines: List<Str>, s: Str, count: I64) -> List<Str> { width <- 60 chars <- Str.to_utf8(s) len <- List.len(chars) doubled <- List.concat(chars, List.take_first(chars, width)) pos <- 1 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(List.sublist(doubled, pos, line)), "\n")) pos <- pos + line if (pos > len) pos <- pos - len remaining <- remaining - line } lines}
random_fasta <- function(lines: List<Str>, genes: List<Gene>, count: I64, seed: I64) -> Record{lines: List<Str>, seed: I64} { width <- 60 lookup_size <- 4096i64 lookup_scale <- Num.to_f64(lookup_size - 1) n <- List.len(genes) cprob_lookup <- List.map(genes, \(gene) gene$probability * lookup_scale) cprob_lookup[[n]] <- Num.to_f64(lookup_size - 1)
lookup <- List.repeat(0, lookup_size) j <- 1i64 for (i in List.range(1, lookup_size)) { while (cprob_lookup[[j]] + 1 < Num.to_f64(i)) j <- j + 1 lookup[[i]] <- j }
remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) rs <- List.repeat(0, line) for (i in List.range(1, line)) { seed <- (seed * 3877 + 29573) %% 139968 rs[[i]] <- Num.to_f64(seed) * (lookup_scale / 139968) }
inds <- List.map(rs, \(r) lookup[[Num.truncate(r) + 1]]) missed <- missed_lookups(cprob_lookup, inds, rs) while (!List.is_empty(missed)) { for (i in missed) inds[[i]] <- inds[[i]] + 1 missed <- missed_lookups(cprob_lookup, inds, rs) } bytes <- List.map(inds, \(index) genes[[index]]$code) lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(bytes), "\n")) remaining <- remaining - line } (lines = lines, seed = seed)}
# The positions whose lookup landed below its random number.missed_lookups <- function(cprob_lookup: List<F64>, inds: List<I64>, rs: List<F64>) -> List<I64> { List.keep_if(List.range(1, List.len(rs)), \(i) cprob_lookup[[inds[[i]]]] < rs[[i]])}
# ---------------------------------------------------------------------------# Driver: the same as fastaredux.R's, except that the typed program returns its lines and the# driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(80000)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fastaredux %s %.4f\n", checksum, seconds))})Fasta-redux, scalar lookup fastaredux_naive 4.07x
Fasta-redux that does the table lookup and its correction one character at a time in a scalar loop Source
execute <- function(n=80000) { width = 60L lookup_size = 4096L lookup_scale = as.double(lookup_size - 1L)
alu = paste( "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA", sep="", collapse="")
iub = matrix(c( c(0.27, 'a'), c(0.12, 'c'), c(0.12, 'g'), c(0.27, 't'), c(0.02, 'B'), c(0.02, 'D'), c(0.02, 'H'), c(0.02, 'K'), c(0.02, 'M'), c(0.02, 'N'), c(0.02, 'R'), c(0.02, 'S'), c(0.02, 'V'), c(0.02, 'W'), c(0.02, 'Y') ), 2)
homosapiens = matrix(c( c(0.3029549426680, 'a'), c(0.1979883004921, 'c'), c(0.1975473066391, 'g'), c(0.3015094502008, 't') ), 2)
random <- 42L random_next_lookup <- function() { random <<- (random * 3877L + 29573L) %% 139968L return(random * (lookup_scale / 139968)) # TODO }
repeat_fasta <- function(s, count) { chars = strsplit(s, split="")[[1]] len = nchar(s) s2 <- character(len + width) for (i in 1:len) s2[[i]] <- chars[[i]] for (i in 1:width) s2[[len + i]] <- chars[[i]] pos <- 1L while (count) { line = min(width, count) next_pos <- pos + line cat(paste(s2[pos:(next_pos - 1)], collapse="", sep=""), "\n", sep="") pos <- next_pos if (pos > len) pos <- pos - len count <- count - line } }
random_fasta <- function(genelist, count) { n = ncol(genelist) lookup <- integer(lookup_size) cprob_lookup <- cumsum(genelist[1, ]) * lookup_scale cprob_lookup[[n]] <- lookup_size - 1
j <- 1L for (i in 1:lookup_size) { while (cprob_lookup[[j]] + 1L < i) j <- j + 1L lookup[[i]] <- j }
while (count) { line <- min(width, count) seq <- character(line) for (i in 1:line) { r <- random_next_lookup() ind <- lookup[[r + 1L]] if (cprob_lookup[[ind]] < r) repeat { ind <- ind + 1L if (!(cprob_lookup[[ind]] < r)) break } seq[[i]] <- genelist[[2, ind]] } cat(paste(seq, collapse="", sep=""), "\n", sep="") count <- count - line } }
fastaredux_naive <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 1000L cat(">ONE Homo sapiens alu\n") repeat_fasta(alu, 2 * n) cat(">TWO IUB ambiguity codes\n") random_fasta(iub, 3L * n) cat(">THREE Homo sapiens frequency\n") random_fasta(homosapiens, 5L * n) }
fastaredux_naive(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(80000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fastaredux_naive %s %.4f\n", checksum, seconds))})alias Gene = Record{probability: F64, code: I64}
execute <- function(n: I64) -> List<Str> { alu <- Str.join_with([ "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA" ], "")
iub <- genes([ (0.27f64, "a"), (0.12f64, "c"), (0.12f64, "g"), (0.27f64, "t"), (0.02f64, "B"), (0.02f64, "D"), (0.02f64, "H"), (0.02f64, "K"), (0.02f64, "M"), (0.02f64, "N"), (0.02f64, "R"), (0.02f64, "S"), (0.02f64, "V"), (0.02f64, "W"), (0.02f64, "Y") ]) homosapiens <- genes([ (0.3029549426680f64, "a"), (0.1979883004921f64, "c"), (0.1975473066391f64, "g"), (0.3015094502008f64, "t") ])
lines <- List.append(repeat_fasta([">ONE Homo sapiens alu\n"], alu, 2 * n), ">TWO IUB ambiguity codes\n") two <- random_fasta(lines, iub, 3 * n, 42) three <- random_fasta(List.append(two$lines, ">THREE Homo sapiens frequency\n"), homosapiens, 5 * n, two$seed) three$lines}
# The cumulative probabilities, each with its code as a byte.genes <- function(table: List<Tuple{F64, Str}>) -> List<Gene> { total: F64 <- 0 genes <- [] for (entry in table) { total <- total + entry[[1]] genes <- List.append(genes, (probability = total, code = Str.to_utf8(entry[[2]])[[1]])) } genes}
repeat_fasta <- function(lines: List<Str>, s: Str, count: I64) -> List<Str> { width <- 60 chars <- Str.to_utf8(s) len <- List.len(chars) doubled <- List.repeat(0, len + width) for (i in List.range(1, len)) doubled[[i]] <- chars[[i]] for (i in List.range(1, width)) doubled[[len + i]] <- chars[[i]] pos <- 1 remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(List.sublist(doubled, pos, line)), "\n")) pos <- pos + line if (pos > len) pos <- pos - len remaining <- remaining - line } lines}
random_fasta <- function(lines: List<Str>, genes: List<Gene>, count: I64, seed: I64) -> Record{lines: List<Str>, seed: I64} { width <- 60 lookup_size <- 4096i64 lookup_scale <- Num.to_f64(lookup_size - 1) n <- List.len(genes) cprob_lookup <- List.map(genes, \(gene) gene$probability * lookup_scale) cprob_lookup[[n]] <- Num.to_f64(lookup_size - 1)
lookup <- List.repeat(0, lookup_size) j <- 1i64 for (i in List.range(1, lookup_size)) { while (cprob_lookup[[j]] + 1 < Num.to_f64(i)) j <- j + 1 lookup[[i]] <- j }
remaining <- count while (remaining > 0) { line <- Num.min(width, remaining) bytes <- List.repeat(0, line) for (i in List.range(1, line)) { seed <- (seed * 3877 + 29573) %% 139968 r <- Num.to_f64(seed) * (lookup_scale / 139968) ind <- lookup[[Num.truncate(r) + 1]] while (cprob_lookup[[ind]] < r) ind <- ind + 1 bytes[[i]] <- genes[[ind]]$code } lines <- List.append(lines, Str.concat(Str.from_utf8_lossy(bytes), "\n")) remaining <- remaining - line } (lines = lines, seed = seed)}
# ---------------------------------------------------------------------------# Driver: the same as fastaredux_naive.R's, except that the typed program returns its lines and the# driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(80000)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("fastaredux_naive %s %.4f\n", checksum, seconds))})K-nucleotide, hashed environment knucleotide 3.76x
Reads a FASTA file and counts k-mer frequencies in a hashed environment with exists, get and assign Source
execute <- function(n=2000) { gen_freq <- function(seq, frame) { frame <- frame - 1L ns <- length(seq) - frame h <- new.env(emptyenv(), hash=TRUE) for (i in 1:ns) { subseq_str = paste(seq[i:(i + frame)], collapse="", sep="") if (exists(subseq_str, h, inherits=FALSE)) cnt <- get(subseq_str, h, inherits=FALSE) else cnt <- 0L assign(subseq_str, cnt + 1L, h) } return(sapply(ls(h), function(k) get(k, h, inherits=FALSE))) }
sort_seq <- function(seq, len) { fs <- gen_freq(seq, len) seqs <- names(fs) inds <- order(-fs, seqs)# cat(paste.(seqs[inds], 100 * fs[inds] / sum(fs), collapse="\n", digits=3), cat(paste(seqs[inds], 100 * fs[inds] / sum(fs), collapse="\n"), "\n") }
find_seq <- function(seq, s) { freqs <- gen_freq(seq, nchar(s)) if (s %in% names(freqs)) return(freqs[[s]]) return(0L) }
knucleotide <- function(args) { in_filename = args[[1]] f <- file(in_filename, "r") print(f) while (length(line <- readLines(f, n=1, warn=FALSE))) { first_char <- substr(line, 1L, 1L) if (first_char == '>' || first_char == ';') if (substr(line, 2L, 3L) == 'TH') break }
n <- 0L cap <- 8L str_buf <- character(cap) while (length(line <- scan(f, what="", nmax=1, quiet=TRUE))) { first_char <- substr(line, 1L, 1L) if (first_char == '>' || first_char == ';') break n <- n + 1L # ensure O(N) resizing (instead of O(N^2)) str_buf[[cap <- if (cap < n) 2L * cap else cap]] <- "" str_buf[[n]] <- line } length(str_buf) <- n close(f) seq <- strsplit(paste(str_buf, collapse=""), split="")[[1]]
for (frame in 1:2) sort_seq(seq, frame) for (s in c("GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT")) cat(find_seq(seq, tolower(s)), sep="\t", s, "\n") }
paste. <- function (..., digits=16, sep=" ", collapse=NULL) { args <- list(...) if (length(args) == 0) if (length(collapse) == 0) character(0) else "" else { for(i in seq(along=args)) if(is.numeric(args[[i]])) args[[i]] <- as.character(round(args[[i]], digits)) else args[[i]] <- as.character(args[[i]]) .Internal(paste(args, sep, collapse)) } }
file <- paste("../fasta/fasta", n, ".txt", sep="") knucleotide(file)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ # The program reads ../fasta/fasta<n>.txt, so write that input with this # suite's fasta.R into a scratch directory first, outside the timed region. generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(generator$execute(4000L), file = file.path(scratch, "fasta", paste0("fasta", 4000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output(value <- execute(4000L)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("knucleotide %s %.4f\n", checksum, seconds))})execute <- function(lines: List<Str>) -> List<Str> { count <- List.len(lines) i <- 1 while (i <= count && !Str.starts_with(lines[[i]], ">TH")) i <- i + 1 i <- i + 1 parts <- [] while (i <= count && !Str.starts_with(lines[[i]], ">") && !Str.starts_with(lines[[i]], ";")) { parts <- List.append(parts, lines[[i]]) i <- i + 1 } sequence <- Str.to_utf8(Str.join_with(parts, ""))
output <- [sorted_frequencies(sequence, 1), sorted_frequencies(sequence, 2)] for (s in ["GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT"]) { lower <- Str.with_ascii_lowercased(s) found <- Result.with_default(Dict.get(frequencies(sequence, List.len(Str.to_utf8(lower))), lower), 0i64) output <- List.append(output, f"{found}\t{s}\t\n") } output}
frequencies <- function(sequence: List<I64>, frame: I64) -> Dict<Str, I64> { counts <- Dict.empty() for (i in List.range(1, List.len(sequence) - frame + 1)) { key <- Str.from_utf8_lossy(List.sublist(sequence, i, frame)) counts <- Dict.update(counts, key, function(found) :Ok(Result.with_default(found, 0i64) + 1i64)) } counts}
sorted_frequencies <- function(sequence: List<I64>, frame: I64) -> Str { entries <- Dict.to_list(frequencies(sequence, frame)) total <- Num.to_f64(List.sum(List.map(entries, \(entry) entry[[2]]))) sorted <- List.sort_with(entries, \(a, b) { match (Num.compare(b[[2]], a[[2]])) { :EQ => if (a[[1]] < b[[1]]) :LT else :GT order => order } }) lines <- List.map(sorted, \(entry) f"{entry[[1]]} {100 * Num.to_f64(entry[[2]]) / total}") Str.concat(Str.join_with(lines, "\n"), " \n")}
# ---------------------------------------------------------------------------# Driver: the same as knucleotide.R's, except that R reads the input file inside the clock# and the typed program returns its output, which the driver prints inside the clock.local({ generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(eval(quote(execute(4000L)), generator), file = file.path(scratch, "fasta", paste0("fasta", 4000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output({ f <- file("../fasta/fasta4000.txt", "r") print(f) lines <- readLines(f, warn = FALSE) close(f) items <- List.from_r(lines) cat(List.to_r(execute(items)), sep = "") }) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("knucleotide %s %.4f\n", checksum, seconds))})K-nucleotide, attribute counts knucleotide_brute 4.17x
K-nucleotide that keeps each k-mer's count as an attribute of an integer vector, read with attr and set with attr<- Source
execute <- function(n=2000) { gen_freq <- function(seq, frame) { frame <- frame - 1L ns <- nchar(seq) - frame freqs <- integer(0) for (i in 1:ns) { subseq = substr(seq, i, i + frame) cnt <- attr(freqs, subseq) if (is.null(cnt)) cnt <- 0L attr(freqs, subseq) <- cnt + 1L } return(freqs) }
gen_freq <- function(seq, frame) { # CTK: duplicate method frame <- frame - 1L ns <- nchar(seq) - frame freqs <- integer(0) for (i in 1:ns) { subseq = substr(seq, i, i + frame) cnt <- attr(freqs, subseq) # CTK: adding exact=TRUE would massively improve performance if (is.null(cnt)) cnt <- 0L attr(freqs, subseq) <- cnt + 1L } return(freqs) }
sort_seq <- function(seq, len) { cnt_map <- gen_freq(seq, len) #print(cnt_map) attrs <- attributes(cnt_map) fs <- unlist(attrs, use.names=FALSE) seqs <- toupper(paste(names(attrs))) inds <- order(-fs, seqs) #cat(paste(seqs[inds], fs[inds], collapse="\n"), "\n") #cat(paste.(seqs[inds], 100 * fs[inds] / sum(fs), collapse="\n", digits=3), cat(paste(seqs[inds], 100 * fs[inds] / sum(fs), collapse="\n"), "\n") }
find_seq <- function(seq, s) { cnt_map <- gen_freq(seq, nchar(s)) if (!is.null(cnt <- attr(cnt_map, s))) return(cnt) return(0L) }
knucleotide_brute <- function(args) { in_filename = args[[1]] f <- file(in_filename, "r") while (length(line <- readLines(f, n=1, warn=FALSE))) { first_char <- substr(line, 1L, 1L) if (first_char == '>' || first_char == ';') if (substr(line, 2L, 3L) == 'TH') break }
n <- 0L cap <- 8L str_buf <- character(cap) while (length(line <- scan(f, what="", nmax=1, quiet=TRUE))) { first_char <- substr(line, 1L, 1L) if (first_char == '>' || first_char == ';') break n <- n + 1L # ensure O(N) resizing (instead of O(N^2)) str_buf[[cap <- if (cap < n) 2L * cap else cap]] <- "" str_buf[[n]] <- line } length(str_buf) <- n close(f)
seq <- paste(str_buf, collapse="")
for (frame in 1:2) sort_seq(seq, frame) for (s in c("GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT")) cat(find_seq(seq, tolower(s)), sep="\t", s, "\n") }
paste. <- function (..., digits=16, sep=" ", collapse=NULL) { args <- list(...) if (length(args) == 0) if (length(collapse) == 0) character(0) else "" else { for(i in seq(along=args)) if(is.numeric(args[[i]])) args[[i]] <- as.character(round(args[[i]], digits)) else args[[i]] <- as.character(args[[i]]) .Internal(paste(args, sep, collapse)) } }
file <- paste("../fasta/fasta", n, ".txt", sep="") knucleotide_brute(file)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ # The program reads ../fasta/fasta<n>.txt, so write that input with this # suite's fasta.R into a scratch directory first, outside the timed region. generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(generator$execute(1000L), file = file.path(scratch, "fasta", paste0("fasta", 1000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output(value <- execute(1000L)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("knucleotide_brute %s %.4f\n", checksum, seconds))})execute <- function(lines: List<Str>) -> List<Str> { count <- List.len(lines) i <- 1i64 while (i <= count && !Str.starts_with(lines[[i]], ">TH")) i <- i + 1 i <- i + 1 parts <- [] while (i <= count && !Str.starts_with(lines[[i]], ">") && !Str.starts_with(lines[[i]], ";")) { parts <- List.append(parts, lines[[i]]) i <- i + 1 } sequence <- Str.to_utf8(Str.join_with(parts, ""))
output <- [sort_seq(sequence, 1), sort_seq(sequence, 2)] for (s in ["GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT"]) { output <- List.append(output, f"{find_seq(sequence, Str.with_ascii_lowercased(s))}\t{s}\t\n") } output}
sort_seq <- function(sequence: List<I64>, frame: I64) -> Str { freqs <- gen_freq(sequence, frame) total <- Num.to_f64(List.sum(freqs$counts)) upper <- List.map2(freqs$names, freqs$counts, \(name, count) (Str.with_ascii_uppercased(name), count)) sorted <- List.sort_with(upper, \(a, b) { match (Num.compare(b[[2]], a[[2]])) { :EQ => if (a[[1]] < b[[1]]) :LT else :GT order => order } }) lines <- List.map(sorted, \(entry) f"{entry[[1]]} {100 * Num.to_f64(entry[[2]]) / total}") Str.concat(Str.join_with(lines, "\n"), " \n")}
find_seq <- function(sequence: List<I64>, s: Str) -> I64 { freqs <- gen_freq(sequence, List.len(Str.to_utf8(s))) match (List.find_first_index(freqs$names, \(name) name == s)) { :Ok(index) => freqs$counts[[index]] :Err(_) => 0i64 }}
gen_freq <- function(sequence: List<I64>, frame: I64) -> Record{names: List<Str>, counts: List<I64>} { names <- [] counts <- [] for (i in List.range(1, List.len(sequence) - frame + 1)) { subseq <- Str.from_utf8_lossy(List.sublist(sequence, i, frame)) match (List.find_first_index(names, \(name) name == subseq)) { :Ok(index) => { counts[[index]] <- counts[[index]] + 1 } :Err(_) => { names <- List.append(names, subseq) counts <- List.append(counts, 1i64) } } } (names = names, counts = counts)}
# ---------------------------------------------------------------------------# Driver: the same as knucleotide_brute.R's, except that R reads the input file inside the clock# and the typed program returns its output, which the driver prints inside the clock.local({ generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(eval(quote(execute(1000L)), generator), file = file.path(scratch, "fasta", paste0("fasta", 1000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output({ f <- file("../fasta/fasta1000.txt", "r") lines <- readLines(f, warn = FALSE) close(f) items <- List.from_r(lines) cat(List.to_r(execute(items)), sep = "") }) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("knucleotide_brute %s %.4f\n", checksum, seconds))})K-nucleotide, attribute counts, growing vector knucleotide_brute_2 3.00x
Attribute-count k-nucleotide that also grows the underlying vector by doubling each time a new k-mer appears Source
execute <- function(n=3000) { gen_freq <- function(seq, frame) { frame <- frame - 1L ns <- nchar(seq) - frame n <- 0L cap <- 16L freqs <- integer(cap) for (i in 1:ns) { subseq = substr(seq, i, i + frame) cnt <- attr(freqs, subseq) if (is.null(cnt)) { cnt <- 0L # ensure O(N) resizing (instead of O(N^2)) n <- n + 1L freqs[[cap <- if (cap < n) 2L * cap else cap]] <- 0L } attr(freqs, subseq) <- cnt + 1L } return(freqs) }
sort_seq <- function(seq, len) { cnt_map <- gen_freq(seq, len) #print(cnt_map) attrs <- attributes(cnt_map) fs <- unlist(attrs, use.names=FALSE) seqs <- toupper(paste(names(attrs))) inds <- order(-fs, seqs) #cat(paste(seqs[inds], fs[inds], collapse="\n"), "\n") #cat(paste.(seqs[inds], 100 * fs[inds] / sum(fs), collapse="\n", digits=3), cat(paste(seqs[inds], 100 * fs[inds] / sum(fs), collapse="\n"), "\n") }
find_seq <- function(seq, s) { cnt_map <- gen_freq(seq, nchar(s)) if (!is.null(cnt <- attr(cnt_map, s))) return(cnt) return(0L) }
knucleotide_brute_2 <- function(args) { in_filename = args[[1]] f <- file(in_filename, "r") while (length(line <- readLines(f, n=1, warn=FALSE))) { first_char <- substr(line, 1L, 1L) if (first_char == '>' || first_char == ';') if (substr(line, 2L, 3L) == 'TH') break }
n <- 0L cap <- 8L str_buf <- character(cap) while (length(line <- scan(f, what="", nmax=1, quiet=TRUE))) { first_char <- substr(line, 1L, 1L) if (first_char == '>' || first_char == ';') break n <- n + 1L # ensure O(N) resizing (instead of O(N^2)) str_buf[[cap <- if (cap < n) 2L * cap else cap]] <- "" str_buf[[n]] <- line } length(str_buf) <- n close(f) seq <- paste(str_buf, collapse="")
for (frame in 1:2) sort_seq(seq, frame) for (s in c("GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT")) cat(find_seq(seq, tolower(s)), sep="\t", s, "\n") }
paste. <- function (..., digits=16, sep=" ", collapse=NULL) { args <- list(...) if (length(args) == 0) if (length(collapse) == 0) character(0) else "" else { for(i in seq(along=args)) if(is.numeric(args[[i]])) args[[i]] <- as.character(round(args[[i]], digits)) else args[[i]] <- as.character(args[[i]]) .Internal(paste(args, sep, collapse)) } }
file <- paste("../fasta/fasta", n, ".txt", sep="") knucleotide_brute_2(file)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ # The program reads ../fasta/fasta<n>.txt, so write that input with this # suite's fasta.R into a scratch directory first, outside the timed region. generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(generator$execute(1500L), file = file.path(scratch, "fasta", paste0("fasta", 1500L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output(value <- execute(1500L)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("knucleotide_brute_2 %s %.4f\n", checksum, seconds))})execute <- function(lines: List<Str>) -> List<Str> { count <- List.len(lines) i <- 1i64 while (i <= count && !Str.starts_with(lines[[i]], ">TH")) i <- i + 1 i <- i + 1 parts <- [] while (i <= count && !Str.starts_with(lines[[i]], ">") && !Str.starts_with(lines[[i]], ";")) { parts <- List.append(parts, lines[[i]]) i <- i + 1 } sequence <- Str.to_utf8(Str.join_with(parts, ""))
output <- [sort_seq(sequence, 1), sort_seq(sequence, 2)] for (s in ["GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT"]) { output <- List.append(output, f"{find_seq(sequence, Str.with_ascii_lowercased(s))}\t{s}\t\n") } output}
sort_seq <- function(sequence: List<I64>, frame: I64) -> Str { freqs <- gen_freq(sequence, frame) total <- Num.to_f64(List.sum(freqs$counts)) upper <- List.map2(freqs$names, freqs$counts, \(name, count) (Str.with_ascii_uppercased(name), count)) sorted <- List.sort_with(upper, \(a, b) { match (Num.compare(b[[2]], a[[2]])) { :EQ => if (a[[1]] < b[[1]]) :LT else :GT order => order } }) lines <- List.map(sorted, \(entry) f"{entry[[1]]} {100 * Num.to_f64(entry[[2]]) / total}") Str.concat(Str.join_with(lines, "\n"), " \n")}
find_seq <- function(sequence: List<I64>, s: Str) -> I64 { freqs <- gen_freq(sequence, List.len(Str.to_utf8(s))) match (List.find_first_index(freqs$names, \(name) name == s)) { :Ok(index) => freqs$counts[[index]] :Err(_) => 0i64 }}
gen_freq <- function(sequence: List<I64>, frame: I64) -> Record{names: List<Str>, counts: List<I64>, slots: List<I64>} { names <- [] counts <- [] n <- 0i64 cap <- 16i64 slots <- List.repeat(0i64, cap) for (i in List.range(1, List.len(sequence) - frame + 1)) { subseq <- Str.from_utf8_lossy(List.sublist(sequence, i, frame)) match (List.find_first_index(names, \(name) name == subseq)) { :Ok(index) => { counts[[index]] <- counts[[index]] + 1 } :Err(_) => { n <- n + 1 if (cap < n) { cap <- 2 * cap slots <- List.concat(slots, List.repeat(0i64, cap - List.len(slots))) } slots[[cap]] <- 0i64 names <- List.append(names, subseq) counts <- List.append(counts, 1i64) } } } (names = names, counts = counts, slots = slots)}
# ---------------------------------------------------------------------------# Driver: the same as knucleotide_brute_2.R's, except that R reads the input file inside the clock# and the typed program returns its output, which the driver prints inside the clock.local({ generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(eval(quote(execute(1500L)), generator), file = file.path(scratch, "fasta", paste0("fasta", 1500L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output({ f <- file("../fasta/fasta1500.txt", "r") lines <- readLines(f, warn = FALSE) close(f) items <- List.from_r(lines) cat(List.to_r(execute(items)), sep = "") }) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("knucleotide_brute_2 %s %.4f\n", checksum, seconds))})K-nucleotide, named vector counts knucleotide_brute_3 5.52x
K-nucleotide that keeps the counts in a named integer vector, indexed and assigned by k-mer name Source
execute <- function(n=2000) { gen_freq <- function(seq, frame) { frame <- frame - 1L ns <- nchar(seq) - frame n <- 0L cap <- 16L freqs <- integer(cap) for (i in 1:ns) { subseq = substr(seq, i, i + frame) #if (subseq %in% names(freqs)) # cnt <- freqs[[subseq]] cnt <- freqs[subseq] if (is.na(cnt)) { #else { cnt <- 0L # ensure O(N) resizing (instead of O(N^2)) n <- n + 1L
#CTK - this optimization has no (positive) effect because the expanded space does not #CTK have the names we will need; it has a detrimental effect, instead (even with GNU-R) freqs[[cap <- if (cap < n) 2L * cap else cap]] <- 0L } freqs[[subseq]] <- cnt + 1L } return(freqs) }
sort_seq <- function(seq, len) { cnt_map <- gen_freq(seq, len) #print(cnt_map)
#CTK needed these changes to make the benchmark work in GNU-R #CTK attrs <- attributes(cnt_map) #CTK fs <- unlist(attrs, use.names=FALSE) #CTK seqs <- toupper(paste(names(attrs)))
#CTK --- added lines starting from here fs <- cnt_map[cnt_map > 0] seqs <- toupper(paste(names(fs))) #CTK --- end of added lines
inds <- order(-fs, seqs) #cat(paste(seqs[inds], fs[inds], collapse="\n"), "\n")# cat(paste.(seqs[inds], 100 * fs[inds] / sum(fs), collapse="\n", digits=3), cat(paste(seqs[inds], 100 * fs[inds] / sum(fs), collapse="\n"), "\n") }
find_seq <- function(seq, s) { cnt_map <- gen_freq(seq, nchar(s))
#CTK if (!is.null(cnt <- attr(cnt_map, s))) if (!is.na(cnt <- cnt_map[s])) return(cnt) return(0L) }
knucleotide_brute_3 <- function(args) { in_filename = args[[1]] f <- file(in_filename, "r") while (length(line <- readLines(f, n=1, warn=FALSE))) { first_char <- substr(line, 1L, 1L) if (first_char == '>' || first_char == ';') if (substr(line, 2L, 3L) == 'TH') break }
n <- 0L cap <- 8L str_buf <- character(cap) while (length(line <- scan(f, what="", nmax=1, quiet=TRUE))) { first_char <- substr(line, 1L, 1L) if (first_char == '>' || first_char == ';') break n <- n + 1L # ensure O(N) resizing (instead of O(N^2)) str_buf[[cap <- if (cap < n) 2L * cap else cap]] <- "" str_buf[[n]] <- line } length(str_buf) <- n close(f) seq <- paste(str_buf, collapse="")
for (frame in 1:2) sort_seq(seq, frame) for (s in c("GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT")) cat(find_seq(seq, tolower(s)), sep="\t", s, "\n") }
paste. <- function (..., digits=16, sep=" ", collapse=NULL) { args <- list(...) if (length(args) == 0) if (length(collapse) == 0) character(0) else "" else { for(i in seq(along=args)) if(is.numeric(args[[i]])) args[[i]] <- as.character(round(args[[i]], digits)) else args[[i]] <- as.character(args[[i]]) .Internal(paste(args, sep, collapse)) } }
file <- paste("../fasta/fasta", n, ".txt", sep="") knucleotide_brute_3(file)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ # The program reads ../fasta/fasta<n>.txt, so write that input with this # suite's fasta.R into a scratch directory first, outside the timed region. generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(generator$execute(1000L), file = file.path(scratch, "fasta", paste0("fasta", 1000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output(value <- execute(1000L)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("knucleotide_brute_3 %s %.4f\n", checksum, seconds))})execute <- function(lines: List<Str>) -> List<Str> { count <- List.len(lines) i <- 1i64 while (i <= count && !Str.starts_with(lines[[i]], ">TH")) i <- i + 1 i <- i + 1 parts <- [] while (i <= count && !Str.starts_with(lines[[i]], ">") && !Str.starts_with(lines[[i]], ";")) { parts <- List.append(parts, lines[[i]]) i <- i + 1 } sequence <- Str.to_utf8(Str.join_with(parts, ""))
output <- [sort_seq(sequence, 1), sort_seq(sequence, 2)] for (s in ["GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT"]) { output <- List.append(output, f"{find_seq(sequence, Str.with_ascii_lowercased(s))}\t{s}\t\n") } output}
sort_seq <- function(sequence: List<I64>, frame: I64) -> Str { freqs <- gen_freq(sequence, frame) entries <- List.keep_if(List.map2(freqs$names, freqs$counts, \(name, count) (name, count)), \(entry) entry[[2]] > 0) total <- Num.to_f64(List.sum(List.map(entries, \(entry) entry[[2]]))) upper <- List.map(entries, \(entry) (Str.with_ascii_uppercased(entry[[1]]), entry[[2]])) sorted <- List.sort_with(upper, \(a, b) { match (Num.compare(b[[2]], a[[2]])) { :EQ => if (a[[1]] < b[[1]]) :LT else :GT order => order } }) lines <- List.map(sorted, \(entry) f"{entry[[1]]} {100 * Num.to_f64(entry[[2]]) / total}") Str.concat(Str.join_with(lines, "\n"), " \n")}
find_seq <- function(sequence: List<I64>, s: Str) -> I64 { freqs <- gen_freq(sequence, List.len(Str.to_utf8(s))) match (List.find_first_index(freqs$names, \(name) name == s)) { :Ok(index) => freqs$counts[[index]] :Err(_) => 0i64 }}
gen_freq <- function(sequence: List<I64>, frame: I64) -> Record{names: List<Str>, counts: List<I64>} { n <- 0i64 cap <- 16i64 names <- List.repeat("", cap) counts <- List.repeat(0i64, cap) for (i in List.range(1, List.len(sequence) - frame + 1)) { subseq <- Str.from_utf8_lossy(List.sublist(sequence, i, frame)) index <- Result.with_default(List.find_first_index(names, \(name) name == subseq), 0i64) cnt <- if (index == 0i64) 0i64 else counts[[index]] if (index == 0i64) { n <- n + 1 if (cap < n) cap <- 2 * cap if (cap > List.len(counts)) { names <- List.concat(names, List.repeat("", cap - List.len(names))) counts <- List.concat(counts, List.repeat(0i64, cap - List.len(counts))) } counts[[cap]] <- 0i64 names <- List.append(names, subseq) counts <- List.append(counts, cnt + 1) } else { counts[[index]] <- cnt + 1 } } (names = names, counts = counts)}
# ---------------------------------------------------------------------------# Driver: the same as knucleotide_brute_3.R's, except that R reads the input file inside the clock# and the typed program returns its output, which the driver prints inside the clock.local({ generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(eval(quote(execute(1000L)), generator), file = file.path(scratch, "fasta", paste0("fasta", 1000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output({ f <- file("../fasta/fasta1000.txt", "r") lines <- readLines(f, warn = FALSE) close(f) items <- List.from_r(lines) cat(List.to_r(execute(items)), sep = "") }) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("knucleotide_brute_3 %s %.4f\n", checksum, seconds))})Mandelbrot, vectorized rows mandelbrot_ascii 1.58x
Iterates complex vectors one 1,300-point row at a time, packs the bits into raw bytes and prints them Source
execute <- function(n=300) { lim <- 2 iter <- 50
mandelbrot_ascii <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 200L n_mod8 = n %% 8L pads <- if (n_mod8) rep.int(0, 8L - n_mod8) else integer(0) p <- rep(as.integer(rep.int(2, 8) ^ (7:0)), length.out=n)
cat("P4\n") cat(n, n, "\n") for (y in 0:(n-1)) { c <- 2 * 0:(n-1) / n - 1.5 + 1i * (2 * y / n - 1) z <- rep(0+0i, n) i <- 0L while (i < iter) { # faster than for loop z <- z * z + c i <- i + 1L } bits <- as.integer(abs(z) <= lim) bytes <- as.raw(colSums(matrix(c(bits * p, pads), 8L))) cat(bytes,"\n") } }
mandelbrot_ascii(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1300)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("mandelbrot_ascii %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> List<Str> { lim <- 2f64 iter <- 50 fn <- Num.to_f64(n) n_mod8 <- n %% 8 pads <- List.repeat(0i64, if (n_mod8 > 0) 8 - n_mod8 else 0i64) p <- List.map(List.range(0, n - 1), \(x) Num.pow_int(2i64, 7 - x %% 8)) hex <- Str.to_utf8("0123456789abcdef")
output <- ["P4\n", f"{n} {n} \n"] for (y in List.range(0, n - 1)) { cr <- List.map(List.range(0, n - 1), \(x) 2 * Num.to_f64(x) / fn - 1.5) ci <- 2 * Num.to_f64(y) / fn - 1 zr <- List.repeat(0f64, n) zi <- List.repeat(0f64, n) i <- 0 while (i < iter) { next_zr <- List.map3(zr, zi, cr, \(r, im, c) if (r * r + im * im > 4) r else r * r - im * im + c) zi <- List.map2(zr, zi, \(r, im) if (r * r + im * im > 4) im else r * im * 2 + ci) zr <- next_zr i <- i + 1 } bits <- List.map2(zr, zi, \(r, im) if (Num.sqrt(r * r + im * im) <= lim) 1i64 else 0i64) bytes <- List.map(List.chunks_of(List.concat(bits * p, pads), 8), \(chunk) List.sum(chunk)) line <- List.join_map(bytes, \(byte) [hex[[byte %/% 16 + 1]], hex[[byte %% 16 + 1]], 32i64]) output <- List.append(output, Str.concat(Str.from_utf8_lossy(line), "\n")) } output}
# ---------------------------------------------------------------------------# Driver: the same as mandelbrot_ascii.R's, except that the typed program returns its# output and the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(1300)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("mandelbrot_ascii %s %.4f\n", checksum, seconds))})Mandelbrot, scalar points mandelbrot_naive_ascii 2.71x
Iterates each point as a complex scalar with an escape test, packing bits into bytes one point at a time Source
execute <- function(n=200) {
lim <- 2 iter <- 50
mandelbrot_naive_ascii <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 200L cat("P4\n") cat(n, n, "\n") for (y in 0:(n-1)) { bits <- 0L x <- 0L while (x < n) { c <- 2 * x / n - 1.5 + 1i * (2 * y / n - 1) z <- 0+0i i <- 0L while (i < iter && abs(z) <= lim) { z <- z * z + c i <- i + 1L } bits <- 2L * bits + as.integer(abs(z) <= lim) if ((x <- x + 1L) %% 8L == 0) { cat(as.raw(bits), "\n") bits <- 0L } } xmod <- x %% 8L if (xmod) cat(as.raw(bits * as.integer(2^(8L - xmod))), "\n") } }
mandelbrot_naive_ascii(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(300)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("mandelbrot_naive_ascii %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> List<Str> { lim <- 2f64 iter <- 50 hex <- Str.to_utf8("0123456789abcdef") fn <- Num.to_f64(n) output <- ["P4\n", f"{n} {n} \n"] for (y in List.range(0, n - 1)) { bits <- 0i64 x <- 0i64 while (x < n) { cr <- 2 * Num.to_f64(x) / fn - 1.5 ci <- 2 * Num.to_f64(y) / fn - 1 zr <- 0f64 zi <- 0f64 i <- 0 while (i < iter && Num.sqrt(zr * zr + zi * zi) <= lim) { next_zr <- zr * zr - zi * zi + cr zi <- 2 * zr * zi + ci zr <- next_zr i <- i + 1 } bits <- 2 * bits + (if (Num.sqrt(zr * zr + zi * zi) <= lim) 1i64 else 0i64) x <- x + 1 if (x %% 8 == 0) { output <- List.append(output, Str.concat(Str.from_utf8_lossy([hex[[bits %/% 16 + 1]], hex[[bits %% 16 + 1]]]), " \n")) bits <- 0i64 } } xmod <- x %% 8 if (xmod != 0) { byte <- bits * Num.pow_int(2i64, 8 - xmod) output <- List.append(output, Str.concat(Str.from_utf8_lossy([hex[[byte %/% 16 + 1]], hex[[byte %% 16 + 1]]]), " \n")) } } output}
# ---------------------------------------------------------------------------# Driver: the same as mandelbrot_naive_ascii.R's, except that the typed program returns its# output and the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(300)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("mandelbrot_naive_ascii %s %.4f\n", checksum, seconds))})Mandelbrot, vectorized rows, no output mandelbrot_noout 1.60x
The vectorized-row Mandelbrot without printing the bitmap, so the time is complex vector arithmetic Source
execute <- function(n=400) { lim <- 2 iter <- 50
mandelbrot_noout <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 200L n_mod8 = n %% 8L pads <- if (n_mod8) rep.int(0, 8L - n_mod8) else integer(0) p <- rep(as.integer(rep.int(2, 8) ^ (7:0)), length.out=n)
cat("P4\n") cat(n, n, "\n") #bin_con <- pipe("cat", "wb") for (y in 0:(n-1)) { c <- 2 * 0:(n-1) / n - 1.5 + 1i * (2 * y / n - 1) z <- rep(0+0i, n) i <- 0L while (i < iter) { # faster than for loop z <- z * z + c i <- i + 1L } bits <- as.integer(abs(z) <= lim) bytes <- as.raw(colSums(matrix(c(bits * p, pads), 8L))) } }
mandelbrot_noout(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1200)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("mandelbrot_noout %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> List<Str> { lim <- 2f64 iter <- 50 fn <- Num.to_f64(n) n_mod8 <- n %% 8 pads <- List.repeat(0i64, if (n_mod8 > 0) 8 - n_mod8 else 0i64) p <- List.map(List.range(0, n - 1), \(x) Num.pow_int(2i64, 7 - x %% 8))
output <- ["P4\n", f"{n} {n} \n"] for (y in List.range(0, n - 1)) { cr <- List.map(List.range(0, n - 1), \(x) 2 * Num.to_f64(x) / fn - 1.5) ci <- 2 * Num.to_f64(y) / fn - 1 zr <- List.repeat(0f64, n) zi <- List.repeat(0f64, n) i <- 0 while (i < iter) { next_zr <- List.map3(zr, zi, cr, \(r, im, c) if (r * r + im * im > 4) r else r * r - im * im + c) zi <- List.map2(zr, zi, \(r, im) if (r * r + im * im > 4) im else r * im * 2 + ci) zr <- next_zr i <- i + 1 } bits <- List.map2(zr, zi, \(r, im) if (Num.sqrt(r * r + im * im) <= lim) 1i64 else 0i64) bytes <- List.map(List.chunks_of(List.concat(bits * p, pads), 8), \(chunk) List.sum(chunk)) } output}
# ---------------------------------------------------------------------------# Driver: the same as mandelbrot_noout.R's, except that the typed program returns its# output and the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(1200)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("mandelbrot_noout %s %.4f\n", checksum, seconds))})Mandelbrot, whole-plane matrix mandelbrot_noout_naive 1.36x
Iterates a 1,000 x 1,000 complex matrix 20 times, storing exp(-abs(Z)) into slices of a 3-D array Source
execute <- function(n=500) { lim <- 2 iter <- 50
mandelbrot_noout_naive <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 200L n_mod8 = n %% 8L pads <- if (n_mod8) rep.int(0, 8L - n_mod8) else integer(0) p <- rep(as.integer(rep.int(2, 8) ^ (7:0)), length.out=n)
cat("P4\n") cat(n, n, "\n") C <- matrix(0, n, n) for (y in 0:(n-1)) { C[, y] <- 2 * 0:(n-1) / n - 1.5 + 1i * (2 * y / n - 1) }
m <- n Z <- 0 # initialize Z to zero X <- array(0, c(m,m,20)) # initialize output 3D array for (k in 1:20) { # loop with 20 iterations Z <- Z^2+C # the central difference equation X[,,k] <- exp(-abs(Z)) # capture results } }
mandelbrot_noout_naive(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("mandelbrot_noout_naive %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> List<Str> { fn <- Num.to_f64(n) output <- ["P4\n", f"{n} {n} \n"]
# R's `C[, 0] <- ...` assigns nothing, so the first row's values never land, and the last # column keeps the zero it starts with. cr <- List.repeat(0f64, n * n) ci <- List.repeat(0f64, n * n) for (y in List.range(1, n - 1)) { for (x in List.range(0, n - 1)) { cr[[(y - 1) * n + x + 1]] <- 2 * Num.to_f64(x) / fn - 1.5 ci[[(y - 1) * n + x + 1]] <- 2 * Num.to_f64(y) / fn - 1 } }
m <- n zr <- List.repeat(0f64, m * m) zi <- List.repeat(0f64, m * m) planes <- List.repeat(List.repeat(0f64, m * m), 20) for (k in List.range(1, 20)) { next_zr <- List.map3(zr, zi, cr, \(r, im, c) if (r * r + im * im > 4) r else r * r - im * im + c) zi <- List.map3(zr, zi, ci, \(r, im, c) if (r * r + im * im > 4) im else r * im * 2 + c) zr <- next_zr planes[[k]] <- List.map2(zr, zi, \(r, im) Num.exp(0 - Num.sqrt(r * r + im * im))) } output}
# ---------------------------------------------------------------------------# Driver: the same as mandelbrot_noout_naive.R's, except that the typed program returns its# output and the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(1000)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("mandelbrot_noout_naive %s %.4f\n", checksum, seconds))})N-body nbody 1.87x
Simulates five planets with one coordinate vector per axis, using outer() and %*% at each of 40,000 steps Source
execute <- function(n=25000) { pi <- 3.141592653589793 solar_mass <- 4 * pi * pi days_per_year <- 365.24 n_bodies <- 5
body_x <- c( 0, # sun 4.84143144246472090e+00, # jupiter 8.34336671824457987e+00, # saturn 1.28943695621391310e+01, # uranus 1.53796971148509165e+01 # neptune ) body_y <- c( 0, # sun -1.16032004402742839e+00, # jupiter 4.12479856412430479e+00, # saturn -1.51111514016986312e+01, # uranus -2.59193146099879641e+01 # neptune ) body_z <- c( 0, # sun -1.03622044471123109e-01, # jupiter -4.03523417114321381e-01, # saturn -2.23307578892655734e-01, # uranus 1.79258772950371181e-01 # neptune )
body_vx <- c( 0, # sun 1.66007664274403694e-03 * days_per_year, # jupiter -2.76742510726862411e-03 * days_per_year, # saturn 2.96460137564761618e-03 * days_per_year, # uranus 2.68067772490389322e-03 * days_per_year # neptune ) body_vy <- c( 0, # sun 7.69901118419740425e-03 * days_per_year, # jupiter 4.99852801234917238e-03 * days_per_year, # saturn 2.37847173959480950e-03 * days_per_year, # uranus 1.62824170038242295e-03 * days_per_year # neptune ) body_vz <- c( 0, # sun -6.90460016972063023e-05 * days_per_year, # jupiter 2.30417297573763929e-05 * days_per_year, # saturn -2.96589568540237556e-05 * days_per_year, # uranus -9.51592254519715870e-05 * days_per_year # neptune )
body_mass <- c( solar_mass, # sun 9.54791938424326609e-04 * solar_mass, # jupiter 2.85885980666130812e-04 * solar_mass, # saturn 4.36624404335156298e-05 * solar_mass, # uranus 5.15138902046611451e-05 * solar_mass # neptune )
offset_momentum <- function() { body_vx[[1]] <<- -sum(body_vx * body_mass) / solar_mass body_vy[[1]] <<- -sum(body_vy * body_mass) / solar_mass body_vz[[1]] <<- -sum(body_vz * body_mass) / solar_mass }
advance <- function(dt) { dxx <- outer(body_x, body_x, "-") # ~2x faster then nested for loops dyy <- outer(body_y, body_y, "-") dzz <- outer(body_z, body_z, "-") distance <- sqrt(dxx * dxx + dyy * dyy + dzz * dzz) mag <- dt / (distance * distance * distance) # ~fast as distance^3 diag(mag) <- 0 body_vx <<- body_vx - as.vector((dxx * mag) %*% body_mass) body_vy <<- body_vy - as.vector((dyy * mag) %*% body_mass) body_vz <<- body_vz - as.vector((dzz * mag) %*% body_mass) body_x <<- body_x + dt * body_vx body_y <<- body_y + dt * body_vy body_z <<- body_z + dt * body_vz }
energy <- function() { dxx <- outer(body_x, body_x, "-") dyy <- outer(body_y, body_y, "-") dzz <- outer(body_z, body_z, "-") distance <- sqrt(dxx * dxx + dyy * dyy + dzz * dzz) q <- (body_mass %o% body_mass) / distance return(sum(0.5 * body_mass * (body_vx * body_vx + body_vy * body_vy + body_vz * body_vz)) - sum(q[upper.tri(q)])) }
nbody <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 1000L options(digits=9) offset_momentum() cat(energy(), "\n") for (i in 1:n) advance(0.01) cat(energy(), "\n") }
nbody(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(40000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("nbody %s %.4f\n", checksum, seconds))})alias Body = Record{x: F64, y: F64, z: F64, vx: F64, vy: F64, vz: F64, mass: F64}
execute <- function(n: I64) -> Record{before: F64, after: F64} { pi <- 3.141592653589793f64 solar_mass <- 4 * pi * pi days_per_year <- 365.24f64
bodies <- [ # sun (x = 0f64, y = 0f64, z = 0f64, vx = 0f64, vy = 0f64, vz = 0f64, mass = solar_mass), # jupiter ( x = 4.84143144246472090e+00f64, y = -1.16032004402742839e+00f64, z = -1.03622044471123109e-01f64, vx = 1.66007664274403694e-03f64 * days_per_year, vy = 7.69901118419740425e-03f64 * days_per_year, vz = -6.90460016972063023e-05f64 * days_per_year, mass = 9.54791938424326609e-04f64 * solar_mass ), # saturn ( x = 8.34336671824457987e+00f64, y = 4.12479856412430479e+00f64, z = -4.03523417114321381e-01f64, vx = -2.76742510726862411e-03f64 * days_per_year, vy = 4.99852801234917238e-03f64 * days_per_year, vz = 2.30417297573763929e-05f64 * days_per_year, mass = 2.85885980666130812e-04f64 * solar_mass ), # uranus ( x = 1.28943695621391310e+01f64, y = -1.51111514016986312e+01f64, z = -2.23307578892655734e-01f64, vx = 2.96460137564761618e-03f64 * days_per_year, vy = 2.37847173959480950e-03f64 * days_per_year, vz = -2.96589568540237556e-05f64 * days_per_year, mass = 4.36624404335156298e-05f64 * solar_mass ), # neptune ( x = 1.53796971148509165e+01f64, y = -2.59193146099879641e+01f64, z = 1.79258772950371181e-01f64, vx = 2.68067772490389322e-03f64 * days_per_year, vy = 1.62824170038242295e-03f64 * days_per_year, vz = -9.51592254519715870e-05f64 * days_per_year, mass = 5.15138902046611451e-05f64 * solar_mass ) ]
bodies <- offset_momentum(bodies, solar_mass) before <- energy(bodies) for (step in List.range(1, n)) bodies <- advance(bodies, 0.01) (before = before, after = energy(bodies))}
offset_momentum <- function(bodies: List<Body>, solar_mass: F64) -> List<Body> { px <- List.sum(List.map(bodies, \(b) b$vx * b$mass)) py <- List.sum(List.map(bodies, \(b) b$vy * b$mass)) pz <- List.sum(List.map(bodies, \(b) b$vz * b$mass)) sun <- bodies[[1]] bodies[[1]] <- (..sun, vx = -px / solar_mass, vy = -py / solar_mass, vz = -pz / solar_mass) bodies}
advance <- function(bodies: List<Body>, dt: F64) -> List<Body> { count <- List.len(bodies) moved <- bodies for (i in List.range(1, count)) { a <- bodies[[i]] ax: F64 <- 0 ay: F64 <- 0 az: F64 <- 0 for (j in List.range(1, count)) { if (j != i) { b <- bodies[[j]] dx <- a$x - b$x dy <- a$y - b$y dz <- a$z - b$z distance <- Num.sqrt(dx * dx + dy * dy + dz * dz) mag <- dt / (distance * distance * distance) ax <- ax + dx * mag * b$mass ay <- ay + dy * mag * b$mass az <- az + dz * mag * b$mass } } vx <- a$vx - ax vy <- a$vy - ay vz <- a$vz - az moved[[i]] <- (..a, x = a$x + dt * vx, y = a$y + dt * vy, z = a$z + dt * vz, vx = vx, vy = vy, vz = vz) } moved}
energy <- function(bodies: List<Body>) -> F64 { count <- List.len(bodies) kinetic <- List.sum(List.map(bodies, \(b) 0.5 * b$mass * (b$vx * b$vx + b$vy * b$vy + b$vz * b$vz))) potential: F64 <- 0 for (j in List.range(1, count)) { for (i in List.range(1, j - 1)) { a <- bodies[[i]] b <- bodies[[j]] dx <- a$x - b$x dy <- a$y - b$y dz <- a$z - b$z potential <- potential + a$mass * b$mass / Num.sqrt(dx * dx + dy * dy + dz * dz) } } kinetic - potential}
# ---------------------------------------------------------------------------# Driver: the same as nbody.R's, except that the typed program returns the two energies# it prints and the driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output({ options(digits = 9) result <- execute(40000) cat(result$before, "\n") value <- cat(result$after, "\n") }) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("nbody %s %.4f\n", checksum, seconds))})N-body, matrix state nbody_2 1.82x
N-body with positions in 3 x 5 matrices and pairwise distances filled into a 3-D array by nested loops, then aperm Source
execute <- function(n=12000) { pi <- 3.141592653589793 solar_mass <- 4 * pi * pi days_per_year <- 365.24 n_bodies <- 5
body_r <- matrix(c( c( # sun 0, 0, 0), c( # jupiter 4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01), c( # saturn 8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01), c( # uranus 1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01), c( # neptune 1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01) ), 3)
body_v <- matrix(c( c( #sun 0, 0, 0), c( # jupiter 1.66007664274403694e-03 * days_per_year, 7.69901118419740425e-03 * days_per_year, -6.90460016972063023e-05 * days_per_year), c( # saturn -2.76742510726862411e-03 * days_per_year, 4.99852801234917238e-03 * days_per_year, 2.30417297573763929e-05 * days_per_year), c( # uranus 2.96460137564761618e-03 * days_per_year, 2.37847173959480950e-03 * days_per_year, -2.96589568540237556e-05 * days_per_year), c( # neptune 2.68067772490389322e-03 * days_per_year, 1.62824170038242295e-03 * days_per_year, -9.51592254519715870e-05 * days_per_year) ), 3)
body_mass <- c( solar_mass, # sun 9.54791938424326609e-04 * solar_mass, # jupiter 2.85885980666130812e-04 * solar_mass, # saturn 4.36624404335156298e-05 * solar_mass, # uranus 5.15138902046611451e-05 * solar_mass # neptune )
offset_momentum <- function() { body_v[, 1] <<- -(body_v %*% body_mass) / solar_mass }
advance <- function(dt) { drr <- array(dim=c(n_bodies, n_bodies, 3)) for (i in 1:n_bodies) { for (j in 1:n_bodies) { drr[i, j,] <- body_r[,i] - body_r[,j] } }
distance <- sqrt(t(colSums(aperm(drr * drr)))) mag <- dt / (distance * distance * distance) # ~fast as distance^3 diag(mag) <- 0 for (d in 1:3) body_v[d,] <<- body_v[d,] - as.vector((drr[,,d] * mag) %*% body_mass)
body_r <<- body_r + dt * body_v }
energy <- function() { drr <- array(dim=c(n_bodies, n_bodies, 3)) for (i in 1:n_bodies) { for (j in 1:n_bodies) drr[i, j,] <- body_r[,i] - body_r[,j] } distance <- sqrt(t(colSums(aperm(drr * drr)))) q <- (body_mass %o% body_mass) / distance return(sum(0.5 * body_mass * colSums(body_v * body_v)) - sum(q[upper.tri(q)])) }
nbody_2 <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 1000L options(digits=9) offset_momentum() cat(energy(), "\n") for (i in 1:n) advance(0.01) cat(energy(), "\n") }
nbody_2(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(20000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("nbody_2 %s %.4f\n", checksum, seconds))})alias State = Record{r: List<F64>, v: List<F64>}
execute <- function(n: I64) -> Record{before: F64, after: F64} { pi <- 3.141592653589793f64 solar_mass <- 4 * pi * pi days_per_year <- 365.24f64
r <- [ # sun 0f64, 0f64, 0f64, # jupiter 4.84143144246472090e+00f64, -1.16032004402742839e+00f64, -1.03622044471123109e-01f64, # saturn 8.34336671824457987e+00f64, 4.12479856412430479e+00f64, -4.03523417114321381e-01f64, # uranus 1.28943695621391310e+01f64, -1.51111514016986312e+01f64, -2.23307578892655734e-01f64, # neptune 1.53796971148509165e+01f64, -2.59193146099879641e+01f64, 1.79258772950371181e-01f64 ] v <- [ # sun 0f64, 0f64, 0f64, # jupiter 1.66007664274403694e-03f64 * days_per_year, 7.69901118419740425e-03f64 * days_per_year, -6.90460016972063023e-05f64 * days_per_year, # saturn -2.76742510726862411e-03f64 * days_per_year, 4.99852801234917238e-03f64 * days_per_year, 2.30417297573763929e-05f64 * days_per_year, # uranus 2.96460137564761618e-03f64 * days_per_year, 2.37847173959480950e-03f64 * days_per_year, -2.96589568540237556e-05f64 * days_per_year, # neptune 2.68067772490389322e-03f64 * days_per_year, 1.62824170038242295e-03f64 * days_per_year, -9.51592254519715870e-05f64 * days_per_year ] mass <- [ solar_mass, 9.54791938424326609e-04f64 * solar_mass, 2.85885980666130812e-04f64 * solar_mass, 4.36624404335156298e-05f64 * solar_mass, 5.15138902046611451e-05f64 * solar_mass ]
# offset_momentum: the sun's velocity is -(body_v %*% body_mass) / solar_mass. momentum <- times_vector(v, 3, mass) for (d in List.range(1, 3)) v[[d]] <- 0 - momentum[[d]] / solar_mass
state <- (r = r, v = v) before <- energy(state, mass) for (i in List.range(1, n)) state <- advance(state, mass, 0.01) (before = before, after = energy(state, mass))}
# m %*% x for a matrix m with `rows` rows, summing the columns scaled by x.times_vector <- function(m: List<F64>, rows: I64, x: List<F64>) -> List<F64> List.walk(List.range(1, List.len(x)), List.repeat(0f64, rows), \(sum, j) sum + List.sublist(m, (j - 1) * rows + 1, rows) * x[[j]])
# drr[i, j, ] <- body_r[, i] - body_r[, j]differences <- function(r: List<F64>) -> List<F64> { n_bodies <- 5i64 drr <- List.repeat(0f64, n_bodies * n_bodies * 3) for (i in List.range(1, n_bodies)) { for (j in List.range(1, n_bodies)) { for (d in List.range(1, 3)) { drr[[(d - 1) * n_bodies * n_bodies + (j - 1) * n_bodies + i]] <- r[[(i - 1) * 3 + d]] - r[[(j - 1) * 3 + d]] } } } drr}
# sqrt(t(colSums(aperm(drr * drr)))): the distance between bodies i and j at [i, j].distances <- function(drr: List<F64>) -> List<F64> { squares <- drr * drr List.map(List.sublist(squares, 1, 25) + List.sublist(squares, 26, 25) + List.sublist(squares, 51, 25), \(square) Num.sqrt(square))}
advance <- function(state: State, mass: List<F64>, dt: F64) -> State { n_bodies <- 5i64 drr <- differences(state$r) distance <- distances(drr) mag <- List.map(distance, \(x) dt / (x * x * x)) for (i in List.range(1, n_bodies)) mag[[(i - 1) * n_bodies + i]] <- 0f64 v <- state$v for (d in List.range(1, 3)) { pull <- times_vector(List.sublist(drr, (d - 1) * 25 + 1, 25) * mag, n_bodies, mass) for (i in List.range(1, n_bodies)) v[[(i - 1) * 3 + d]] <- v[[(i - 1) * 3 + d]] - pull[[i]] } (r = state$r + v * dt, v = v)}
energy <- function(state: State, mass: List<F64>) -> F64 { n_bodies <- 5i64 distance <- distances(differences(state$r)) squares <- state$v * state$v speeds <- List.map(List.range(1, n_bodies), \(i) List.sum(List.sublist(squares, (i - 1) * 3 + 1, 3))) kinetic <- List.sum(mass * 0.5 * speeds) potential <- 0f64 for (j in List.range(1, n_bodies)) { if (j > 1) { for (i in List.range(1, j - 1)) potential <- potential + mass[[i]] * mass[[j]] / distance[[(j - 1) * n_bodies + i]] } } kinetic - potential}
# ---------------------------------------------------------------------------# Driver: the same as nbody_2.R's, except that the typed program returns the two energies# it prints and the driver prints them inside the clock.local({ started <- proc.time()[[3]] output <- capture.output({ options(digits = 9) result <- execute(20000) cat(Num.to_r(result$before), "\n") value <- cat(Num.to_r(result$after), "\n") }) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("nbody_2 %s %.4f\n", checksum, seconds))})Pi digits pidigits 2.78x
Prints 55 digits of pi with a spigot over a hand-written bignum on base-10,000 integer vectors Source
# Constructors and string conversion functions
execute <- function(n=30) { zero_mag = integer(0) zero = c(0L, zero_mag) # ( = 0L ) one_mag = c(1L) one = c(1L, one_mag) ten_mag = c(10L) ten = c(1L, ten_mag)
elem_max = 10000 elem_digits = as.integer(log10(elem_max))
signum <- function(v) v[[1]] mag <- function(v) v[2:length(v)]
str_to_mag <- function(s) { strip_leading_zeros <- function(s) { for (i in 1:nchar(s)) if (substr(s, i, i) != '0') return(substr(s, i, nchar(s))) return("") }
len = nchar(s <- strip_leading_zeros(s)) if (len == 0) return(zero_mag) mod <- len %% elem_digits if (mod > 0) chunks <- substr(s, 1, mod) else chunks <- character(0) if (1 + mod < len) { chunk_inds_begin <- seq(1 + mod, len, elem_digits) chunk_inds_end <- chunk_inds_begin + elem_digits - 1 chunks <- c(chunks, substring(s, chunk_inds_begin, chunk_inds_end)) } return(sapply(chunks, as.integer)) }
bigint <- function(s, i=NA) { if (!is.na(i)) { s <- as.character(i) } if (substr(s, 1, 1) == '-') { mag <- str_to_mag(substr(s, 2L, nchar(s))) sgn <- -1L } else { mag <- str_to_mag(s) sgn <- 1L } return(c(if (length(mag)) sgn else 0L, mag)) }
to_int <- function(x) { ret <- 0L if ((x_len = length(x)) > 1L) for (i in length(x):2) ret <- ret * elem_max + x[[i]] return(x[[1]] * ret) }
mag_to_str <- function(x) { len = length(x) if (len == 1) return(as.character(x[[1]])) xs <- sapply(x[2:length(x)], function(e) zeropad(e, 4)) x1 <- x[[1]] return(paste(collapse="", sep="", c( x[[1]], sapply(x[2:length(x)], function(e) zeropad(e, elem_digits))))) }
to_str <- function(x) { if (x[[1]] == 0L) return("0") return(paste(sep="", if (x[[1]] < 0L) '-' else '', mag_to_str(mag(x)))) }
# Comparison functions
cmp_elem <- function(x, y) (x > y) - (x < y) cmp_mag <- function(x, y) { x_len = length(x) y_len = length(y) if (x_len < y_len) return(-1L) if (x_len > y_len) return(1L) for (i in 1:x_len) if (c <- cmp_elem(x[[i]], y[[i]])) return(c) return(0L) } cmp <- function(x, y) { x_sign = x[[1]] y_sign = y[[1]] if (x_sign == y_sign) { if (x[[1]] == 1L) return(cmp_mag(mag(x), mag(y))) if (x[[1]] == -1L) return(cmp_mag(mag(y), mag(x))) return(0L) } return((x_sign > y_sign) - (x_sign < y_sign)) }
eq <- function(x, y) cmp(x, y) == 0L ne <- function(x, y) cmp(x, y) != 0L le <- function(x, y) cmp(x, y) <= 0L lt <- function(x, y) cmp(x, y) < 0L ge <- function(x, y) cmp(x, y) >= 0L gt <- function(x, y) cmp(x, y) > 0L
# Arithmetic operations
add_mag <- function(x, y) { # if x is shorter, swap the two vectors if (length(x) < length(y)) { tmp <- x; x <- y; y <- tmp } x_len = length(x) y_len = length(y)
x_index <- x_len y_index <- y_len result <- integer(x_len) sum <- 0L
# add common parts of both numbers while (y_index > 0L) { sum <- (x[[x_index]] %% elem_max + y[[y_index]] %% elem_max + sum %/% elem_max) # TODO shift result[[x_index]] <- sum %% elem_max x_index <- x_index - 1L y_index <- y_index - 1L }
# copy remainder of the longer number while carry propagation is required carry <- (sum >= elem_max) while (x_index > 0L & carry) { carry <- (result[[x_index]] <- x[[x_index]] + 1L) == 0L x_index <- x_index - 1L }
# copy remainder of the longer number while (x_index > 0L) { result[[x_index]] <- x[[x_index]] x_index <- x_index - 1L }
# grow result if necessary if (carry) return(c(0x01L, result)) return(result) }
add <- function(x, y) { if (y[[1]] == 0L) return(x) if (x[[1]] == 0L) return(y) if (x[[1]] == y[[1]]) return(c(x[[1]], add_mag(mag(x), mag(y))))
c <- cmp_mag(mag(x), mag(y)) if (c == 0L) return(zero) if (c > 0L) result_mag <- sub_mag(mag(x), mag(y)) else result_mag <- sub_mag(mag(y), mag(x)) return(c(sign_prod(c, x[[1]]), strip_leading_zero_elems(result_mag))) }
sub_mag <- function(big, little) { big_len = length(big) little_len = length(little) result <- integer(big_len) big_index <- big_len little_index <- little_len difference <- 0L
# subtract common parts of both numbers while (little_index > 0L) { difference <- (big[[big_index]] - little[[little_index]] + if (difference < 0L) -1L else 0L) result[[big_index]] <- difference %% elem_max big_index <- big_index - 1L little_index <- little_index - 1L }
# subtract remainder of longer number while borrow propagates borrow <- if (difference < 0L) -1 else 0L while (big_index > 0L && borrow) { borrow <- (result[[big_index]] <- big[[big_index]] - 1L) == -1L big_index <- big_index - 1L }
# copy remainder of the longer number while (big_index > 0L) { result[[big_index]] <- big[[big_index]] big_index <- big_index - 1L }
return(result) }
sub <- function(x, y) { if (y[[1]] == 0L) return(x) if (x[[1]] == 0L) return(negate(y)) if (x[[1]] != y[[1]]) return(c(x[[1]], add_mag(mag(x), mag(y))))
c <- cmp_mag(mag(x), mag(y)) if (c == 0L) return(zero) if (c > 0L) result_mag <- sub_mag(mag(x), mag(y)) else result_mag <- sub_mag(mag(y), mag(x)) return(c(sign_prod(c, x[[1]]), strip_leading_zero_elems(result_mag))) }
negate <- function(x) c(-x[[1]], x[2:length(x)])
multiply_mag <- function(x, y) { x_len = length(x) y_len = length(y) x_start = x_len # remove y_start = y_len # remove c <- integer(x_len + y_len)
carry <- 0L k <- y_start + x_start for (j in seq(y_start, 1L, -1L)) { product = y[[j]] * x[[x_start]] + carry c[k] <- product %% elem_max carry <- product %/% elem_max k <- k - 1L } c[x_start] <- carry
if (x_len <= 1) return(c)
for (i in seq(x_start - 1L, 1L, -1L)) { carry <- 0 k <- y_start + i for (j in seq(y_start, 1L, -1L)) { product = y[[j]] * x[[i]] + c[[k]] + carry c[[k]] <- product %% elem_max carry <- product %/% elem_max k <- k - 1L } c[[i]] <- carry %% elem_max } return(c) }
mul <- function(x, y) { if (y[[1]] == 0L || x[[1]] == 0) return(zero)
return(c(sign_prod(x[[1]], y[[1]]), strip_leading_zero_elems(multiply_mag(mag(x), mag(y))))) }
div_mag <- function(x_mag, y_mag) { if (length(y_mag) == 1L && y_mag == one_mag) return(x_mag)
x <- c(1L, x_mag) y <- c(1L, y_mag) x_mag_log10 = log10_mag(x_mag); y_mag_log10 = log10_mag(y_mag) lo_log10 = x_mag_log10 - y_mag_log10 - (x_mag_log10 != y_mag_log10) hi_log10 <- x_mag_log10 - y_mag_log10 + 1L lo <- bigint_pow10(lo_log10)
# try pruning hi > 10 or lo <= 10 if (lo_log10 == 0L && hi_log10 > 1L) { lo10 = mul(lo, ten) if (gt(mul(lo10, y), x)) hi <- lo10 else { lo <- lo10 hi <- bigint_pow10(hi_log10) } } else hi <- bigint_pow10(hi_log10)
while (lt(lo, hi)) { mid <- div2(add(add(lo, hi), one)) if (le(mul(mid, y), x)) lo <- mid else hi <- sub(mid, one) } return(mag(lo)) }
div <- function(x, y) { # check if division by zero if (x[[1]] == 0L) return(zero) c <- cmp_mag(mag(x), mag(y)) if (c == 0L) return(one) if (c < 0L) return(zero) return(c(sign_prod(x[[1]], y[[1]]), div_mag(mag(x), mag(y)))) }
# Helper arithmetic functions
div2_mag <- function(x) { x_len <- length(x) if (x_len == 1L) return(x %/% 2L)
borrow <- (x[[1]] == 1) x_start <- borrow + 1L x_end <- x_len result_index <- 1L result <- integer(x_end - x_start + 1L) for (x_index in x_start:x_end) { d = x[[x_index]] + elem_max * borrow result[[result_index]] <- d %/% 2 borrow <- d %% 2 result_index <- result_index + 1L } return(result) }
div2 <- function(x) { if (x[[1]] == 0L || (length(x) == 2L && x[[2]] == 1L)) return(zero) return(c(x[[1]], div2_mag(mag(x)))) }
log10_mag <- function(m) elem_digits * (length(m) - 1L) + as.integer(log(m[[1]], 10))
bigint_pow10 <- function(n) c(1L, as.integer(10^(n %% elem_digits)), rep.int(0L, n %/% elem_digits))
# Misc functions sign_prod <- function(x, y) (x == y) - (x != y) strip_leading_zero_elems <- function(x) { for (i in 1:length(x)) if (x[[i]] != 0L) return(x[i:length(x)]) return(zero_mag) }
zeropad <- function(s, n) paste(sep="", paste(collapse="", rep('0', max(0L, n - nchar(s)))), s)
# PIDIGITS program
pidigits <- function(args) { N = if (length(args)) as.integer(args[[1]]) else 100L ONE = one TWO = bigint("2") TEN = bigint("10") THREE = add(ONE, TWO) i <- k <- ns <- 0L k1 <- 1L a <- t <- u <- bigint("0") n <- d <- bigint("1") while (TRUE) { k <- k + 1L t <- mul(n, TWO) n <- mul(n, bigint(k)) a <- add(a, t) k1 <- k1 + 2L k1_big <- bigint(i=k1) a <- mul(a, k1_big) d <- mul(d, k1_big) if (ge(a, n)) { n3a <- add(mul(n, THREE), a) t <- div(n3a, d) td = mul(t, d) u <- add(sub(n3a, td), n) if (gt(d, u)) { ns <- ns * 10L + to_int(t) i <- i + 1L if (i %% 5L == 0L) { cat(zeropad(as.character(ns), 5)) if (i %% 2L == 0L) cat(sep="", "\t:", i, "\n") ns = 0L } if (i >= N) break a <- sub(a, td) # TODO use td a <- mul(a, TEN) n <- mul(n, TEN) } } } }
pidigits(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(55)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("pidigits %s %.4f\n", checksum, seconds))})alias Nat = List<I64>alias Int = Record{sign: I64, magnitude: Nat}
execute <- function(digits: I64) -> List<Str> { one <- int(1) two <- int(2) three <- int(3) ten <- int(10) i: I64 <- 0 k: I64 <- 0 ns: I64 <- 0 k1: I64 <- 1 a <- int(0) n <- one d <- one output <- [] while (Bool.true) { k <- k + 1 t <- times(n, two) n <- times(n, int(k)) a <- plus(a, t) k1 <- k1 + 2 a <- times(a, int(k1)) d <- times(d, int(k1)) if (!int_less(a, n)) { n3a <- plus(times(n, three), a) t <- quotient(n3a, d) td <- times(t, d) u <- plus(minus(n3a, td), n) if (int_less(u, d)) { ns <- ns * 10 + t$sign * List.sum(t$magnitude) i <- i + 1 if (i %% 5 == 0) { output <- List.append(output, zero_pad(ns, 5)) if (i %% 2 == 0) output <- List.append(output, f"\t:{i}\n") ns <- 0i64 } if (i >= digits) return(output) a <- minus(a, td) a <- times(a, ten) n <- times(n, ten) } } } output}
int <- function(value: I64) -> Int signed(1, nat(value))
signed <- function(sign: I64, magnitude: Nat) -> Int (sign = if (List.is_empty(magnitude)) 0 else sign, magnitude = magnitude)
plus <- function(x: Int, y: Int) -> Int { if (x$sign == 0) return(y) if (y$sign == 0) return(x) if (x$sign == y$sign) return(signed(x$sign, add(x$magnitude, y$magnitude))) match (compare(x$magnitude, y$magnitude)) { :EQ => int(0) :GT => signed(x$sign, subtract(x$magnitude, y$magnitude)) :LT => signed(y$sign, subtract(y$magnitude, x$magnitude)) }}
minus <- function(x: Int, y: Int) -> Int plus(x, (..y, sign = -y$sign))
times <- function(x: Int, y: Int) -> Int signed(x$sign * y$sign, multiply(x$magnitude, y$magnitude))
quotient <- function(x: Int, y: Int) -> Int signed(x$sign * y$sign, divide(x$magnitude, y$magnitude))
int_less <- function(x: Int, y: Int) -> Bool { if (x$sign != y$sign) return(x$sign < y$sign) if (x$sign > 0) return(less(x$magnitude, y$magnitude)) if (x$sign < 0) return(less(y$magnitude, x$magnitude)) Bool.false}
nat <- function(value: I64) -> Nat { limbs <- [] rest <- value while (rest > 0) { limbs <- List.append(limbs, rest %% 10000) rest <- rest %/% 10000 } limbs}
compare <- function(x: Nat, y: Nat) -> :LT | :EQ | :GT { if (List.len(x) != List.len(y)) return(Num.compare(List.len(x), List.len(y))) i <- List.len(x) while (i >= 1) { if (x[[i]] != y[[i]]) return(Num.compare(x[[i]], y[[i]])) i <- i - 1 } :EQ}
less <- function(x: Nat, y: Nat) -> Bool { match (compare(x, y)) { :LT => Bool.true _ => Bool.false }}
add <- function(x: Nat, y: Nat) -> Nat { result <- [] carry: I64 <- 0 for (i in List.range(1, Num.max(List.len(x), List.len(y)))) { sum <- carry + limb(x, i) + limb(y, i) result <- List.append(result, sum %% 10000) carry <- sum %/% 10000 } if (carry > 0) List.append(result, carry) else result}
# `x - y` for `x >= y`.subtract <- function(x: Nat, y: Nat) -> Nat { result <- [] borrow: I64 <- 0 for (i in List.range(1, List.len(x))) { difference <- x[[i]] - limb(y, i) - borrow if (difference < 0) { result <- List.append(result, difference + 10000) borrow <- 1i64 } else { result <- List.append(result, difference) borrow <- 0i64 } } trim(result)}
multiply <- function(x: Nat, y: Nat) -> Nat { if (List.is_empty(x) || List.is_empty(y)) return([]) result <- List.repeat(0i64, List.len(x) + List.len(y)) for (i in List.range(1, List.len(x))) { carry: I64 <- 0 for (j in List.range(1, List.len(y))) { product <- result[[i + j - 1]] + x[[i]] * y[[j]] + carry result[[i + j - 1]] <- product %% 10000 carry <- product %/% 10000 } result[[i + List.len(y)]] <- carry } trim(result)}
divide <- function(x: Nat, y: Nat) -> Nat { match (compare(x, y)) { :LT => [] :EQ => nat(1) :GT => { if (List.len(y) == 1 && y[[1]] == 1) return(x) x_log10 <- log10(x) y_log10 <- log10(y) lo_log10 <- x_log10 - y_log10 - (if (x_log10 != y_log10) 1 else 0) hi_log10 <- x_log10 - y_log10 + 1 lo <- pow10(lo_log10) hi <- pow10(hi_log10) if (lo_log10 == 0 && hi_log10 > 1) { lo10 <- multiply(lo, nat(10)) if (less(x, multiply(lo10, y))) { hi <- lo10 } else { lo <- lo10 } } while (less(lo, hi)) { mid <- half(add(add(lo, hi), nat(1))) if (less(x, multiply(mid, y))) { hi <- subtract(mid, nat(1)) } else { lo <- mid } } lo } }}
half <- function(x: Nat) -> Nat { result <- x remainder: I64 <- 0 i <- List.len(x) while (i >= 1) { value <- remainder * 10000 + x[[i]] result[[i]] <- value %/% 2 remainder <- value %% 2 i <- i - 1 } trim(result)}
# The number of decimal digits less one.log10 <- function(x: Nat) -> I64 { top <- x[[List.len(x)]] count: I64 <- 0 while (top >= 10) { top <- top %/% 10 count <- count + 1 } 4 * (List.len(x) - 1) + count}
pow10 <- function(exponent: I64) -> Nat List.append(List.repeat(0i64, exponent %/% 4), Num.pow_int(10, exponent %% 4))
limb <- function(x: Nat, i: I64) -> I64 if (i <= List.len(x)) x[[i]] else 0
trim <- function(x: Nat) -> Nat { result <- x while (!List.is_empty(result) && result[[List.len(result)]] == 0) result <- List.drop_last(result, 1) result}
zero_pad <- function(value: I64, width: I64) -> Str { text <- f"{value}" Str.concat(Str.repeat("0", Num.max(0, width - List.len(Str.to_utf8(text)))), text)}
# ---------------------------------------------------------------------------# Driver: the same as pidigits.R's, except that the typed program returns its output and# the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output(cat(List.to_r(execute(55)), sep = "")) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("pidigits %s %.4f\n", checksum, seconds))})Regex DNA regexdna 3.07x
Counts nine DNA patterns with gregexpr and expands IUB codes with gsub over one large string Source
execute <- function(n=500000L) { pattern1 <- c( "agggtaaa|tttaccct", "[cgt]gggtaaa|tttaccc[acg]", "a[act]ggtaaa|tttacc[agt]t", "ag[act]gtaaa|tttac[agt]ct", "agg[act]taaa|ttta[agt]cct", "aggg[acg]aaa|ttt[cgt]ccct", "agggt[cgt]aa|tt[acg]accct", "agggta[cgt]a|t[acg]taccct", "agggtaa[cgt]|[acg]ttaccct")
pattern2 <- matrix(c( c("B", "(c|g|t)"), c("D", "(a|g|t)"), c("H", "(a|c|t)"), c("K", "(g|t)"), c("M", "(a|c)"), c("N", "(a|c|g|t)"), c("R", "(a|g)"), c("S", "(c|g)"), c("V", "(a|c|g)"), c("W", "(a|t)"), c("Y", "(c|t)") ), ncol=2, byrow=TRUE)
match_count <- function(ms) { l <- length(ms[[1]]) fst <- ms[[1]][[1]] return(if (l > 1) l else if (fst != -1L) fst else 0) }
regexdna <- function(args) { in_filename = args[[1]] f <- file(in_filename, "r") str <- paste(c(readLines(f), ""), collapse="\n") close(f)
len1 <- nchar(str) str <- gsub(">.*\n|\n", "", str, perl=TRUE, useBytes=TRUE) len2 <- nchar(str)
for (pat in pattern1) cat(pat, match_count(gregexpr(pat, str, useBytes=TRUE)), "\n")
for (i in 1:nrow(pattern2)) str <- gsub(pattern2[[i, 1]], pattern2[[i, 2]], str, perl=TRUE, useBytes=TRUE)
cat("", len1, len2, nchar(str), sep="\n") }
file <- paste("../fasta/fasta", n, ".txt", sep="") regexdna(file)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ # The program reads ../fasta/fasta<n>.txt, so write that input with this # suite's fasta.R into a scratch directory first, outside the timed region. generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(generator$execute(300000L), file = file.path(scratch, "fasta", paste0("fasta", 300000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output(value <- execute(300000L)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("regexdna %s %.4f\n", checksum, seconds))})alias Alternative = List<List<I64>>
execute <- function(lines: List<Str>) -> List<Str> { pattern1 <- [ "agggtaaa|tttaccct", "[cgt]gggtaaa|tttaccc[acg]", "a[act]ggtaaa|tttacc[agt]t", "ag[act]gtaaa|tttac[agt]ct", "agg[act]taaa|ttta[agt]cct", "aggg[acg]aaa|ttt[cgt]ccct", "agggt[cgt]aa|tt[acg]accct", "agggta[cgt]a|t[acg]taccct", "agggtaa[cgt]|[acg]ttaccct" ] pattern2 <- [ ("B", "(c|g|t)"), ("D", "(a|g|t)"), ("H", "(a|c|t)"), ("K", "(g|t)"), ("M", "(a|c)"), ("N", "(a|c|g|t)"), ("R", "(a|g)"), ("S", "(c|g)"), ("V", "(a|c|g)"), ("W", "(a|t)"), ("Y", "(c|t)") ]
str <- Str.join_with(List.append(lines, ""), "\n") len1 <- Str.count_utf8_bytes(str) str <- drop_headers(str) len2 <- Str.count_utf8_bytes(str)
output <- [] bytes <- Str.to_utf8(str) for (pat in pattern1) { output <- List.append(output, f"{pat} {match_count(bytes, parse_pattern(pat))} \n") }
for (substitution in pattern2) str <- Str.replace_each(str, substitution[[1]], substitution[[2]])
List.append(output, f"\n{len1}\n{len2}\n{Str.count_utf8_bytes(str)}")}
# gsub(">.*\n|\n", "", str)drop_headers <- function(str: Str) -> Str { bytes <- Str.to_utf8(str) newline <- 10i64 kept <- List.with_capacity(List.len(bytes)) i <- 1i64 while (i <= List.len(bytes)) { if (bytes[[i]] == 62) { while (i <= List.len(bytes) && bytes[[i]] != newline) i <- i + 1 } else if (bytes[[i]] != newline) { kept <- List.append(kept, bytes[[i]]) } i <- i + 1 } Str.from_utf8_lossy(kept)}
parse_pattern <- function(pattern: Str) -> List<Alternative> { List.map(Str.split_on(pattern, "|"), \(alternative) { bytes <- Str.to_utf8(alternative) positions <- [] i <- 1i64 while (i <= List.len(bytes)) { if (bytes[[i]] == 91) { class <- [] i <- i + 1 while (bytes[[i]] != 93) { class <- List.append(class, bytes[[i]]) i <- i + 1 } positions <- List.append(positions, class) } else { positions <- List.append(positions, [bytes[[i]]]) } i <- i + 1 } positions })}
# The R program's match_count(gregexpr(pat, str)): the number of non-overlapping matches, except# that a single match counts as its position, as written upstream.match_count <- function(bytes: List<I64>, alternatives: List<Alternative>) -> I64 { count <- 0i64 first <- 0i64 i <- 1i64 while (i <= List.len(bytes)) { found <- List.find_first(alternatives, \(alternative) matches_at(bytes, i, alternative)) match (found) { :Ok(alternative) => { count <- count + 1 if (first == 0) first <- i i <- i + List.len(alternative) } :Err(_) => { i <- i + 1 } } } if (count > 1) count else first}
matches_at <- function(bytes: List<I64>, start: I64, alternative: Alternative) -> Bool { if (start + List.len(alternative) - 1 > List.len(bytes)) return(Bool.false) k <- 1i64 while (k <= List.len(alternative)) { if (!List.contains(alternative[[k]], bytes[[start + k - 1]])) return(Bool.false) k <- k + 1 } Bool.true}
# ---------------------------------------------------------------------------# Driver: the same as regexdna.R's, except that R reads the input file inside the clock and# the typed program returns its output, which the driver prints inside the clock.local({ generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(eval(quote(execute(300000L)), generator), file = file.path(scratch, "fasta", paste0("fasta", 300000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output({ f <- file("../fasta/fasta300000.txt", "r") lines <- readLines(f) close(f) items <- List.from_r(lines) value <- cat(List.to_r(execute(items)), sep = "") }) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("regexdna %s %.4f\n", checksum, seconds))})Reverse complement reversecomplement 7.42x
Reads a FASTA file line by line and maps each line's characters through a named vector in one vectorized lookup Source
execute <- function(n=150000L) { codes <- c( "A", "C", "G", "T", "U", "M", "R", "W", "S", "Y", "K", "V", "H", "D", "B", "N") complements <- c( "T", "G", "C", "A", "A", "K", "Y", "W", "S", "R", "M", "B", "D", "H", "V", "N") comp_map <- NULL comp_map[codes] <- complements comp_map[tolower(codes)] <- complements
reversecomplement <- function(args) { in_filename = args[[1]] f <- file(in_filename, "r") while (length(s <- readLines(f, n=1, warn=FALSE))) { codes <- strsplit(s, split="")[[1]] if (codes[[1]] == '>') cat(s, "\n", sep="") else { cat(paste(comp_map[codes], collapse=""), "\n", sep="") } } close(f) }
file <- paste("../fasta/fasta", n, ".txt", sep="") reversecomplement(file)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ # The program reads ../fasta/fasta<n>.txt, so write that input with this # suite's fasta.R into a scratch directory first, outside the timed region. generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(generator$execute(80000L), file = file.path(scratch, "fasta", paste0("fasta", 80000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output(value <- execute(80000L)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("reversecomplement %s %.4f\n", checksum, seconds))})execute <- function(lines: List<Str>) -> List<Str> { codes <- Str.to_utf8("ACGTUMRWSYKVHDBN") complements <- Str.to_utf8("TGCAAKYWSRMBDHVN") lower_codes <- Str.to_utf8("acgtumrwsykvhdbn") table <- Dict.empty() for (i in List.range(1, List.len(codes))) { table <- Dict.insert(table, codes[[i]], complements[[i]]) table <- Dict.insert(table, lower_codes[[i]], complements[[i]]) }
List.map(lines, \(line) { if (Str.starts_with(line, ">")) { Str.concat(line, "\n") } else { bytes <- List.map(Str.to_utf8(line), \(byte) Result.with_default(Dict.get(table, byte), byte)) Str.concat(Str.from_utf8_lossy(bytes), "\n") } })}
# ---------------------------------------------------------------------------# Driver: the same as reversecomplement.R's, except that R reads the input file inside the# clock and the typed program returns its output, which the driver prints inside the clock.# The result is `close()`'s, as in the R program.local({ generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(eval(quote(execute(80000L)), generator), file = file.path(scratch, "fasta", paste0("fasta", 80000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output({ f <- file("../fasta/fasta80000.txt", "r") lines <- readLines(f, warn = FALSE) items <- List.from_r(lines) cat(List.to_r(execute(items)), sep = "") value <- close(f) }) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("reversecomplement %s %.4f\n", checksum, seconds))})Reverse complement, whole file reversecomplement_2 9.88x
Reverse complement that reads the whole file with one readLines call before mapping each line Source
execute <- function(n=150000L) { codes <- c( "A", "C", "G", "T", "U", "M", "R", "W", "S", "Y", "K", "V", "H", "D", "B", "N") complements <- c( "T", "G", "C", "A", "A", "K", "Y", "W", "S", "R", "M", "B", "D", "H", "V", "N") comp_map <- NULL comp_map[codes] <- complements comp_map[tolower(codes)] <- complements
reversecomplement_2 <- function(args) { f <- file(args[[1]], "r") lines <- readLines(f) for (i in 1:length(lines)) { codes <- strsplit(lines[[i]], split="")[[1]] if (codes[[1]] == '>') cat(lines[[i]], "\n", sep="") else { cat(paste(comp_map[codes], collapse=""), "\n", sep="") } } close(f) }
file <- paste("../fasta/fasta", n, ".txt", sep="") reversecomplement_2(file)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ # The program reads ../fasta/fasta<n>.txt, so write that input with this # suite's fasta.R into a scratch directory first, outside the timed region. generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(generator$execute(100000L), file = file.path(scratch, "fasta", paste0("fasta", 100000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output(value <- execute(100000L)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("reversecomplement_2 %s %.4f\n", checksum, seconds))})execute <- function(lines: List<Str>) -> List<Str> { codes <- Str.to_utf8("ACGTUMRWSYKVHDBN") complements <- Str.to_utf8("TGCAAKYWSRMBDHVN") lower_codes <- Str.to_utf8("acgtumrwsykvhdbn") table <- Dict.empty() for (i in List.range(1, List.len(codes))) { table <- Dict.insert(table, codes[[i]], complements[[i]]) table <- Dict.insert(table, lower_codes[[i]], complements[[i]]) }
List.map(lines, \(line) { if (Str.starts_with(line, ">")) { Str.concat(line, "\n") } else { bytes <- List.map(Str.to_utf8(line), \(byte) Result.with_default(Dict.get(table, byte), byte)) Str.concat(Str.from_utf8_lossy(bytes), "\n") } })}
# ---------------------------------------------------------------------------# Driver: the same as reversecomplement_2.R's, except that R reads the input file inside the# clock and the typed program returns its output, which the driver prints inside the clock.# The result is `close()`'s, as in the R program.local({ generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(eval(quote(execute(100000L)), generator), file = file.path(scratch, "fasta", paste0("fasta", 100000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output({ f <- file("../fasta/fasta100000.txt", "r") lines <- readLines(f, warn = FALSE) items <- List.from_r(lines) cat(List.to_r(execute(items)), sep = "") value <- close(f) }) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("reversecomplement_2 %s %.4f\n", checksum, seconds))})Reverse complement, scalar lookup reversecomplement_naive 5.87x
Reverse complement that maps one character at a time with [[ on the named vector in a for loop Source
execute <- function(n=50000) { codes <- c( "A", "C", "G", "T", "U", "M", "R", "W", "S", "Y", "K", "V", "H", "D", "B", "N") complements <- c( "T", "G", "C", "A", "A", "K", "Y", "W", "S", "R", "M", "B", "D", "H", "V", "N") comp_map <- NULL comp_map[codes] <- complements comp_map[tolower(codes)] <- complements
reversecomplement_naive <- function(args) { f <- file(args[[1]], "r") while (length(s <- readLines(f, n=1, warn=FALSE))) { codes <- strsplit(s, split="")[[1]] if (codes[[1]] == '>') cat(s, "\n", sep="") else { for (j in 1:length(codes)) codes[[j]] <- comp_map[[codes[[j]]]] cat(paste(codes, collapse=""), "\n", sep="") } } close(f) }
file <- paste("../fasta/fasta", n, ".txt", sep="") reversecomplement_naive(file)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ # The program reads ../fasta/fasta<n>.txt, so write that input with this # suite's fasta.R into a scratch directory first, outside the timed region. generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(generator$execute(100000L), file = file.path(scratch, "fasta", paste0("fasta", 100000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output(value <- execute(100000L)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("reversecomplement_naive %s %.4f\n", checksum, seconds))})execute <- function(lines: List<Str>) -> List<Str> { codes <- Str.to_utf8("ACGTUMRWSYKVHDBN") complements <- Str.to_utf8("TGCAAKYWSRMBDHVN") lower_codes <- Str.to_utf8("acgtumrwsykvhdbn") table <- Dict.empty() for (i in List.range(1, List.len(codes))) { table <- Dict.insert(table, codes[[i]], complements[[i]]) table <- Dict.insert(table, lower_codes[[i]], complements[[i]]) }
List.map(lines, \(line) { if (Str.starts_with(line, ">")) { Str.concat(line, "\n") } else { chars <- Str.to_utf8(line) for (j in List.range(1, List.len(chars))) chars[[j]] <- Result.with_default(Dict.get(table, chars[[j]]), chars[[j]]) Str.concat(Str.from_utf8_lossy(chars), "\n") } })}
# ---------------------------------------------------------------------------# Driver: the same as reversecomplement_naive.R's, except that R reads the input file inside the# clock and the typed program returns its output, which the driver prints inside the clock.# The result is `close()`'s, as in the R program.local({ generator <- new.env() generator$.ry_bench_loading <- TRUE sys.source("fasta.R", envir = generator) scratch <- tempfile("shootout-") dir.create(file.path(scratch, "fasta"), recursive = TRUE) dir.create(file.path(scratch, "run")) capture.output(eval(quote(execute(100000L)), generator), file = file.path(scratch, "fasta", paste0("fasta", 100000L, ".txt"))) home <- setwd(file.path(scratch, "run")) on.exit({ setwd(home); unlink(scratch, recursive = TRUE) }) started <- proc.time()[[3]] output <- capture.output({ f <- file("../fasta/fasta100000.txt", "r") lines <- readLines(f, warn = FALSE) items <- List.from_r(lines) cat(List.to_r(execute(items)), sep = "") value <- close(f) }) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("reversecomplement_naive %s %.4f\n", checksum, seconds))})Spectral norm spectralnorm 21x
Multiplies by an 800 x 800 matrix once, filling each row with scalar closure calls and taking a %*% dot product Source
execute <- function(n=1200) { spectralnorm <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 100L options(digits=10)
eval_A <- function(i, j) 1 / ((i + j) * (i + j + 1) / 2 + i + 1) eval_A_times_u <- function(u) { ret <- double(n) for (i in 0:n1) { eval_A_col <- double(n) for (j in 0:n1) eval_A_col[[j + 1]] <- eval_A(i, j) ret[[i + 1]] <- u %*% eval_A_col } return(ret) } eval_At_times_u <- function(u) { ret <- double(n) for (i in 0:n1) { eval_At_col <- double(n) for (j in 0:n1) eval_At_col[[j + 1]] <- eval_A(j, i) ret[[i + 1]] <- u %*% eval_At_col } return(ret) } eval_AtA_times_u <- function(u) eval_At_times_u(eval_A_times_u(u))
n1 <- n - 1 u <- rep(1, n) v <- rep(0, n)# was 10 for (itr in seq(1)) { v <- eval_AtA_times_u(u) u <- eval_AtA_times_u(v) }## cat(sqrt(sum(u * v) / sum(v * v)), "\n")#
# sqrt(sum(u * v) / sum(v * v)) u }
spectralnorm(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(800)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> List<F64> { u <- List.repeat(1, n) v <- times_ata(u, n) times_ata(v, n)}
eval_a <- function(i: I64, j: I64) -> F64 1 / Num.to_f64(((i + j) * (i + j + 1)) %/% 2 + i + 1)
times_a <- function(u: List<F64>, n: I64) -> List<F64> List.map(List.range(0, n - 1), \(i) List.sum(List.map(List.range(0, n - 1), \(j) u[[j + 1]] * eval_a(i, j))))
times_at <- function(u: List<F64>, n: I64) -> List<F64> List.map(List.range(0, n - 1), \(i) List.sum(List.map(List.range(0, n - 1), \(j) u[[j + 1]] * eval_a(j, i))))
times_ata <- function(u: List<F64>, n: I64) -> List<F64> times_at(times_a(u, n), n)
# ---------------------------------------------------------------------------# Driver: the same as spectralnorm.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output({ options(digits = 10) result <- execute(800) }) seconds <- proc.time()[[3]] - started value <- List.to_r(result) text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm %s %.4f\n", checksum, seconds))})Spectral norm, precomputed matrix spectralnorm_alt 2.14x
Builds the 3,000 x 3,000 matrix once with outer() and runs 10 power iterations as matrix products Source
execute <- function(n=1500) { spectralnorm_alt <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 100L options(digits=10)
eval_A <- function(i, j) 1 / ((i + j - 2) * (i + j - 1) / 2 + i) eval_A_times_u <- function(u) u %*% g_eval_A_mat eval_At_times_u <- function(u) u %*% g_eval_At_mat eval_AtA_times_u <- function(u) eval_At_times_u(eval_A_times_u(u))
g_eval_A_mat <- outer(seq(n), seq(n), FUN=eval_A) g_eval_At_mat <- t(g_eval_A_mat) u <- rep(1, n) v <- rep(0, n) for (itr in seq(10)) { v <- eval_AtA_times_u(u) u <- eval_AtA_times_u(v) }
cat(sqrt(sum(u * v) / sum(v * v)), "\n") }
spectralnorm_alt(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(3000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm_alt %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> F64 { a <- outer_a(n) at <- transpose(a, n) ata <- \(u) times(times(u, a, n), at, n) u <- List.repeat(1f64, n) v <- List.repeat(0f64, n) for (itr in List.range(1, 10)) { v <- ata(u) u <- ata(v) } Num.sqrt(List.sum(u * v) / List.sum(v * v))}
eval_a <- function(i: I64, j: I64) -> F64 1 / Num.to_f64(((i + j - 2) * (i + j - 1)) %/% 2 + i)
# outer(seq(n), seq(n), FUN = eval_A)outer_a <- function(n: I64) -> List<F64> List.join_map(List.range(1, n), \(j) List.map(List.range(1, n), \(i) eval_a(i, j)))
transpose <- function(m: List<F64>, n: I64) -> List<F64> List.join_map(List.range(1, n), \(j) List.map(List.range(1, n), \(i) m[[(i - 1) * n + j]]))
times <- function(u: List<F64>, m: List<F64>, n: I64) -> List<F64> List.map(List.range(1, n), \(j) List.sum(u * List.sublist(m, (j - 1) * n + 1, n)))
# ---------------------------------------------------------------------------# Driver: the same as spectralnorm_alt.R's, except that the typed program returns the norm and# the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output({ options(digits = 10) cat(Num.to_r(execute(3000)), "\n") }) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm_alt %s %.4f\n", checksum, seconds))})Spectral norm, matrix rebuilt per product spectralnorm_alt_2 3.05x
Spectral norm that rebuilds the 1,200 x 1,200 matrix with outer() for every matrix product Source
execute <- function(n=1200) { spectralnorm_alt_2 <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 100L options(digits=10)
n = if (length(args)) as.integer(args[[1]]) else 100L
eval_A <- function(i, j) 1 / ((i + j - 2) * (i + j - 1) / 2 + i) eval_A_times_u <- function(u) u %*% outer(seq(n), seq(n), FUN=eval_A) eval_At_times_u <- function(u) u %*% t(outer(seq(n), seq(n), FUN=eval_A)) eval_AtA_times_u <- function(u) eval_At_times_u(eval_A_times_u(u))
u <- rep(1, n) v <- rep(0, n) for (itr in seq(10)) { v <- eval_AtA_times_u(u) u <- eval_AtA_times_u(v) } cat(sqrt(sum(u * v) / sum(v * v)), "\n") }
spectralnorm_alt_2(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1200)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm_alt_2 %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> F64 { ata <- \(u) times(times(u, outer_a(n), n), transpose(outer_a(n), n), n) u <- List.repeat(1f64, n) v <- List.repeat(0f64, n) for (itr in List.range(1, 10)) { v <- ata(u) u <- ata(v) } Num.sqrt(List.sum(u * v) / List.sum(v * v))}
eval_a <- function(i: I64, j: I64) -> F64 1 / Num.to_f64(((i + j - 2) * (i + j - 1)) %/% 2 + i)
# outer(seq(n), seq(n), FUN = eval_A)outer_a <- function(n: I64) -> List<F64> List.join_map(List.range(1, n), \(j) List.map(List.range(1, n), \(i) eval_a(i, j)))
transpose <- function(m: List<F64>, n: I64) -> List<F64> List.join_map(List.range(1, n), \(j) List.map(List.range(1, n), \(i) m[[(i - 1) * n + j]]))
times <- function(u: List<F64>, m: List<F64>, n: I64) -> List<F64> List.map(List.range(1, n), \(j) List.sum(u * List.sublist(m, (j - 1) * n + 1, n)))
# ---------------------------------------------------------------------------# Driver: the same as spectralnorm_alt_2.R's, except that the typed program returns the norm and# the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output({ options(digits = 10) cat(Num.to_r(execute(1200)), "\n") }) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm_alt_2 %s %.4f\n", checksum, seconds))})Spectral norm, element-wise matrix fill spectralnorm_alt_3 2.60x
Spectral norm that copies a precomputed table into a fresh matrix with [[i, j]]<- in nested loops for every product Source
execute <- function(n=250) { spectralnorm_alt_3 <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 100L options(digits=10)
eval_A <- function(i, j) eval_A_cache[[i, j]] eval_A_times_u <- function(u) { # eval_A_mat <- outer(seq(n), seq(n), FUN=eval_A) eval_A_mat <- matrix(0, n, n) for (i in 1:n) for (j in 1:n) eval_A_mat[[i, j]] <- eval_A(i, j) return(u %*% t(eval_A_mat)) } eval_At_times_u <- function(u) { # eval_At_mat <- t(outer(seq(n), seq(n), FUN=eval_A)) eval_At_mat <- matrix(0, n, n) for (i in 1:n) for (j in 1:n) eval_At_mat[[i, j]] <- eval_A(i, j) return(u %*% eval_At_mat) } eval_AtA_times_u <- function(u) eval_At_times_u(eval_A_times_u(u)) eval_A_cache <- matrix(0, n, n) for (i in 1:n) for (j in 1:n) eval_A_cache[[i, j]] <- 1/((i + j - 2) * (i + j - 1) / 2 + i) u <- rep(1, n) v <- rep(0, n) for (itr in seq(10)) { v <- eval_AtA_times_u(u) u <- eval_AtA_times_u(v) }
cat(sqrt(sum(u * v) / sum(v * v)), "\n") }
spectralnorm_alt_3(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(250)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm_alt_3 %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> F64 { cache <- List.repeat(0f64, n * n) for (i in List.range(1, n)) for (j in List.range(1, n)) cache[[(j - 1) * n + i]] <- 1 / Num.to_f64(((i + j - 2) * (i + j - 1)) %/% 2 + i)
# Both products copy the cache element by element, as the R program does through eval_A. copy <- \() { m <- List.repeat(0f64, n * n) for (i in List.range(1, n)) for (j in List.range(1, n)) m[[(j - 1) * n + i]] <- cache[[(j - 1) * n + i]] m } ata <- \(u) times(times(u, transpose(copy(), n), n), copy(), n) u <- List.repeat(1f64, n) v <- List.repeat(0f64, n) for (itr in List.range(1, 10)) { v <- ata(u) u <- ata(v) } Num.sqrt(List.sum(u * v) / List.sum(v * v))}
transpose <- function(m: List<F64>, n: I64) -> List<F64> List.join_map(List.range(1, n), \(j) List.map(List.range(1, n), \(i) m[[(i - 1) * n + j]]))
times <- function(u: List<F64>, m: List<F64>, n: I64) -> List<F64> List.map(List.range(1, n), \(j) List.sum(u * List.sublist(m, (j - 1) * n + 1, n)))
# ---------------------------------------------------------------------------# Driver: the same as spectralnorm_alt_3.R's, except that the typed program returns the norm and# the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output({ options(digits = 10) cat(Num.to_r(execute(250)), "\n") }) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm_alt_3 %s %.4f\n", checksum, seconds))})Spectral norm, eigenvalues spectralnorm_math 1.16x
Computes the spectral norm directly as the largest eigenvalue of t(A) %*% A with eigen(), so LAPACK dominates Source
execute <- function(n=1200) { spectralnorm_math <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 100L options(digits=10)
eval_A <- function(i, j) 1 / ((i + j - 2) * (i + j - 1) / 2 + i)
m <- outer(seq(n), seq(n), FUN=eval_A) cat(sqrt(max(eigen(t(m) %*% m)$val)), "\n") }
spectralnorm_math(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm_math %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> F64 { m <- List.join_map(List.range(1, n), \(j) List.map(List.range(1, n), \(i) eval_a(i, j))) # t(m) %*% m: entry (i, j) is the dot product of columns i and j, so the product is symmetric # and each dot product fills two entries. columns <- List.map(List.range(1, n), \(j) List.sublist(m, (j - 1) * n + 1, n)) mtm <- List.repeat(0f64, n * n) for (j in List.range(1, n)) { for (i in List.range(1, j)) { dot <- List.sum(columns[[i]] * columns[[j]]) mtm[[(j - 1) * n + i]] <- dot mtm[[(i - 1) * n + j]] <- dot } } Num.sqrt(List.max(eigenvalues(mtm, n)) |> Result.with_default(0f64))}
eval_a <- function(i: I64, j: I64) -> F64 1 / Num.to_f64(((i + j - 2) * (i + j - 1)) %/% 2 + i)
eigenvalues <- function(matrix: List<F64>, n: I64) -> List<F64> { # a[[i, j]] is a[[(i - 1) * n + j]], row by row, so the loops over k read neighbouring items. # The input is symmetric, so the layout does not change it. a <- matrix d <- List.repeat(0f64, n) e <- List.repeat(0f64, n) i <- n while (i >= 2) { l <- i - 1 h <- 0f64 if (l > 1) { scale <- 0f64 for (k in List.range(1, l)) scale <- scale + Num.abs(a[[(i - 1) * n + k]]) if (scale == 0) { e[[i]] <- a[[(i - 1) * n + l]] } else { for (k in List.range(1, l)) { a[[(i - 1) * n + k]] <- a[[(i - 1) * n + k]] / scale h <- h + a[[(i - 1) * n + k]] * a[[(i - 1) * n + k]] } f <- a[[(i - 1) * n + l]] g <- if (f >= 0) 0 - Num.sqrt(h) else Num.sqrt(h) e[[i]] <- scale * g h <- h - f * g a[[(i - 1) * n + l]] <- f - g f <- 0f64 for (j in List.range(1, l)) { g <- 0f64 for (k in List.range(1, j)) g <- g + a[[(j - 1) * n + k]] * a[[(i - 1) * n + k]] if (l > j) for (k in List.range(j + 1, l)) g <- g + a[[(k - 1) * n + j]] * a[[(i - 1) * n + k]] e[[j]] <- g / h f <- f + e[[j]] * a[[(i - 1) * n + j]] } hh <- f / (h + h) for (j in List.range(1, l)) { f <- a[[(i - 1) * n + j]] g <- e[[j]] - hh * f e[[j]] <- g for (k in List.range(1, j)) a[[(j - 1) * n + k]] <- a[[(j - 1) * n + k]] - (f * e[[k]] + g * a[[(i - 1) * n + k]]) } } } else { e[[i]] <- a[[(i - 1) * n + l]] } d[[i]] <- h i <- i - 1 } for (i in List.range(1, n)) d[[i]] <- a[[(i - 1) * n + i]]
for (i in List.range(2, n)) e[[i - 1]] <- e[[i]] e[[n]] <- 0f64 for (l in List.range(1, n)) { searching <- Bool.true while (searching) { m <- l while (m < n && Num.abs(e[[m]]) + (Num.abs(d[[m]]) + Num.abs(d[[m + 1]])) != Num.abs(d[[m]]) + Num.abs(d[[m + 1]])) m <- m + 1 if (m == l) { searching <- Bool.false } else { g <- (d[[l + 1]] - d[[l]]) / (2 * e[[l]]) r <- Num.sqrt(g * g + 1) g <- d[[m]] - d[[l]] + e[[l]] / (g + (if (g >= 0) r else 0 - r)) s <- 1f64 c <- 1f64 p <- 0f64 i <- m - 1 underflow <- Bool.false while (i >= l && !underflow) { f <- s * e[[i]] b <- c * e[[i]] r <- Num.sqrt(f * f + g * g) e[[i + 1]] <- r if (r == 0) { d[[i + 1]] <- d[[i + 1]] - p e[[m]] <- 0f64 underflow <- Bool.true } else { s <- f / r c <- g / r g <- d[[i + 1]] - p r <- (d[[i]] - g) * s + 2 * c * b p <- s * r d[[i + 1]] <- g + p g <- c * r - b i <- i - 1 } } if (!underflow) { d[[l]] <- d[[l]] - p e[[l]] <- g e[[m]] <- 0f64 } } } } d}
# ---------------------------------------------------------------------------# Driver: the same as spectralnorm_math.R's, except that the typed program returns the norm and# the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output({ options(digits = 10) cat(Num.to_r(execute(1000)), "\n") }) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm_math %s %.4f\n", checksum, seconds))})Spectral norm, scalar loops spectralnorm_naive 23x
Spectral norm with every matrix-vector product as nested scalar loops that call a closure per element Source
execute <- function(n=150) { spectralnorm_naive <- function(args) { n = if (length(args)) as.integer(args[[1]]) else 100L options(digits=10)
eval_A <- function(i, j) 1 / ((i + j) * (i + j + 1) / 2 + i + 1) # TODO: get rid of this hack eval_A_2 <- function(i, j) 1 / ((i + j) * (i + j + 1) / 2 + i + 1)
eval_A_times_u <- function(u) { ret <- rep(0, n) for (i in 1:n) for (j in 0:n1) ret[[i]] <- ret[[i]] + u[[j + 1]] * eval_A(i - 1, j) return(ret) } eval_At_times_u <- function(u) { ret <- rep(0, n) for (i in 1:n) for (j in 0:n1) ret[[i]] <- ret[[i]] + u[[j + 1]] * eval_A_2(j, i - 1) return(ret) } eval_AtA_times_u <- function(u) eval_At_times_u(eval_A_times_u(u))
n1 <- n - 1 u <- rep(1, n) v <- rep(0, n) for (itr in seq(10)) { v <- eval_AtA_times_u(u) u <- eval_AtA_times_u(v) }
cat(sqrt(sum(u * v) / sum(v * v)), "\n") }
spectralnorm_naive(n)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(250)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm_naive %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> F64 { u <- List.repeat(1f64, n) v <- List.repeat(0f64, n) for (itr in List.range(1, 10)) { v <- times_at(times_a(u, n), n) u <- times_at(times_a(v, n), n) } Num.sqrt(List.sum(u * v) / List.sum(v * v))}
eval_a <- function(i: I64, j: I64) -> F64 1 / Num.to_f64(((i + j) * (i + j + 1)) %/% 2 + i + 1)
times_a <- function(u: List<F64>, n: I64) -> List<F64> { ret <- List.repeat(0f64, n) for (i in List.range(1, n)) for (j in List.range(0, n - 1)) ret[[i]] <- ret[[i]] + u[[j + 1]] * eval_a(i - 1, j) ret}
times_at <- function(u: List<F64>, n: I64) -> List<F64> { ret <- List.repeat(0f64, n) for (i in List.range(1, n)) for (j in List.range(0, n - 1)) ret[[i]] <- ret[[i]] + u[[j + 1]] * eval_a(j, i - 1) ret}
# ---------------------------------------------------------------------------# Driver: the same as spectralnorm_naive.R's, except that the typed program returns the norm and# the driver prints it inside the clock.local({ started <- proc.time()[[3]] output <- capture.output({ options(digits = 10) cat(Num.to_r(execute(250)), "\n") }) seconds <- proc.time()[[3]] - started value <- NULL text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("spectralnorm_naive %s %.4f\n", checksum, seconds))})rcp micro-benchmarks and convolutions. The 13 micro-benchmarks of the simple/ directory, each one tight loop that isolates an interpreter cost such as variable assignment, vector subassignment or closure calls, and the 3 convolution programs of RealThing/, which compute the same convolution with scalar loops or vector operations. Source: github.com/PRL-PRG/r-compile-server/tree/b2b13a3150bddcc2d6dae8c37ecbbf1007170940/client/rsh/inst/benchmarks, MIT.
Many local assignments bytecodes 10x
A while loop that assigns the counter to 24 local variables per iteration, 500,000 times Source
execute <- function(n=10000) { a <- 0 b <- 0 c <- 0 d <- 0 e <- 0 f <- 0 g <- 0 h <- 0 i <- 0 j <- 0 k <- 0 l <- 0 m <- 0 o <- 0 p <- 0 q <- 0 r <- 0 s <- 0 t <- 0 u <- 0 v <- 0 w <- 0 x <- 0 y <- 0 z <- 0 while (i < n) { a <- i b <- i c <- i d <- i e <- i f <- i g <- i h <- i j <- i k <- i l <- i m <- i o <- i p <- i q <- i r <- i s <- i t <- i u <- i v <- i w <- i x <- i y <- i z <- i i <- i + 1 } a + b + c + d + e + f + g + h + j + k + l + m + o + p + q + r + s + t + u + v + w + x + y + z}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(500000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("bytecodes %s %.4f\n", checksum, seconds))})execute <- function(n: F64) -> F64 { a: F64 <- 0 b: F64 <- 0 c: F64 <- 0 d: F64 <- 0 e: F64 <- 0 f: F64 <- 0 g: F64 <- 0 h: F64 <- 0 i: F64 <- 0 j: F64 <- 0 k: F64 <- 0 l: F64 <- 0 m: F64 <- 0 o: F64 <- 0 p: F64 <- 0 q: F64 <- 0 r: F64 <- 0 s: F64 <- 0 t: F64 <- 0 u: F64 <- 0 v: F64 <- 0 w: F64 <- 0 x: F64 <- 0 y: F64 <- 0 z: F64 <- 0 while (i < n) { a <- i b <- i c <- i d <- i e <- i f <- i g <- i h <- i j <- i k <- i l <- i m <- i o <- i p <- i q <- i r <- i s <- i t <- i u <- i v <- i w <- i x <- i y <- i z <- i i <- i + 1 } a + b + c + d + e + f + g + h + j + k + l + m + o + p + q + r + s + t + u + v + w + x + y + z}
# ---------------------------------------------------------------------------# Driver: the same as bytecodes.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(500000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("bytecodes %s %.4f\n", checksum, seconds))})Convolution, scalar loops convolution 7.40x
Convolves two 1,000-element vectors 10 times with nested for loops and [ indexing, as in Writing R Extensions Source
execute <- function(n=500) { convolve <- function(a, b) # from the extending R manual { a <- as.double(a) b <- as.double(b) na <- length(a) nb <- length(b) ab <- double(na + nb) for(i in 1 : na) for(j in 1 : nb) ab[i + j] <- ab[i + j] + a[i] * b[j] ab }
a <- 1:n b <- 1:n checksum <- 0 for (i in 1:10) { checksum <- checksum + convolve(a,b)[[n]] } # cat("Convolution ", n, " " , checksum, ": ") checksum}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("convolution %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> F64 { convolve <- function(a: List<F64>, b: List<F64>) -> List<F64> { na <- List.len(a) nb <- List.len(b) ab <- List.repeat(0, na + nb) for (i in List.range(1, na)) for (j in List.range(1, nb)) ab[[i + j]] <- ab[[i + j]] + a[[i]] * b[[j]] ab }
a <- List.map(List.range(1, n), function(i: I64) -> F64 Num.to_f64(i)) b <- List.map(List.range(1, n), function(i: I64) -> F64 Num.to_f64(i)) checksum <- 0 for (i in List.range(1, 10)) { checksum <- checksum + convolve(a, b)[[n]] } checksum}
# ---------------------------------------------------------------------------# Driver: the same as convolution.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(1000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("convolution %s %.4f\n", checksum, seconds))})Convolution, [[ indexing convolution_slow 5.24x
Convolution with nested loops over seq(length =), [[ indexing and the outer element hoisted into a local Source
execute <- function(n=1500) { convolveSlow <- function(x,y) { nx <- length(x) ny <- length(y) z <- numeric(nx + ny - 1) for(i in seq(length = nx)) { xi <- x[[i]] for(j in seq(length = ny)) { ij <- i + j - 1 z[[ij]] <- z[[ij]] + xi * y[[j]] } } z }
a <- 1:n b <- 1:n checksum <- 0 for (i in 1:10) { checksum <- checksum + convolveSlow(a,b)[[n]] } # cat("Convolution ", n, " " , checksum, ": ") checksum}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("convolution_slow %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> F64 { convolve_slow <- function(x: List<I64>, y: List<I64>) -> List<F64> { nx <- List.len(x) ny <- List.len(y) z <- List.repeat(0, nx + ny - 1) for (i in List.range(1, nx)) { xi <- x[[i]] for (j in List.range(1, ny)) { ij <- i + j - 1 z[[ij]] <- z[[ij]] + Num.to_f64(xi * y[[j]]) } } z }
a <- List.range(1, n) b <- List.range(1, n) checksum <- 0 for (i in List.range(1, 10)) { checksum <- checksum + convolve_slow(a, b)[[n]] } checksum}
# ---------------------------------------------------------------------------# Driver: the same as convolution_slow.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(1000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("convolution_slow %s %.4f\n", checksum, seconds))})Convolution, vectorized convolution_v 1.60x
Convolves 1,500-element vectors with outer(), rbind, reshaping through length<- and dim<-, and rowSums Source
execute <- function(n=2000) { convolveV <- function(x, y) { nx <- length(x) ny <- length(y) xy <- rbind(outer(x,y), matrix(0, nx, ny)) nxy <- nx + ny - 1 length(xy) <- nxy * ny dim(xy) <- c(nxy, ny) rowSums(xy) }
a <- 1:n b <- 1:n checksum <- 0 for (i in 1:10) { checksum <- checksum + convolveV(a,b)[[n]] } # cat("Convolution ", n, " " , checksum, ": ") checksum}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1500)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("convolution_v %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> F64 { convolve_v <- function(x: List<F64>, y: List<F64>) -> List<F64> { nx <- List.len(x) ny <- List.len(y) xy <- List.join_map(y, \(yj) List.concat(x * yj, List.repeat(0f64, nx))) nxy <- nx + ny - 1 xy <- List.take_first(xy, nxy * ny) List.walk(List.range(0, ny - 1), List.repeat(0f64, nxy), \(sums, column) sums + List.sublist(xy, column * nxy + 1, nxy)) }
a <- List.map(List.range(1, n), \(i) Num.to_f64(i)) b <- List.map(List.range(1, n), \(i) Num.to_f64(i)) checksum <- 0 for (i in List.range(1, 10)) { checksum <- checksum + convolve_v(a, b)[[n]] } checksum}
# ---------------------------------------------------------------------------# Driver: the same as convolution_v.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(1500)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("convolution_v %s %.4f\n", checksum, seconds))})Empty for loop empty-for 4.11x
Runs a for loop with an empty body over 1:1e8, measuring pure loop overhead Source
execute <- function(n=100000000) { for (i in 1:n) {
}}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1e8)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("empty-for %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> NULL { for (i in List.range(1, n)) {
} NULL}
# ---------------------------------------------------------------------------# Driver: the same as empty-for.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(100000000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("empty-for %s %.4f\n", checksum, seconds))})Counting while loop empty-while 8.20x
Increments a double scalar in a while loop up to 2e7 Source
execute <- function(n=2000000) { x <- 1 while (x < n) { x <- x + 1 } x}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(2e7)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("empty-while %s %.4f\n", checksum, seconds))})execute <- function(n: F64) -> F64 { x <- 1 while (x < n) { x <- x + 1 } x}
# ---------------------------------------------------------------------------# Driver: the same as empty-while.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(20000000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("empty-while %s %.4f\n", checksum, seconds))})lapply with a closure lapply 3.47x
Calls a one-argument closure through lapply over 1e6 integers Source
execute <- function(n=1000000) { x <- 1:n f <- function(x) x + 1.5 lapply(x, f)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1e6)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("lapply %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> List<F64> { x <- List.range(1, n) f <- function(x: I64) -> F64 Num.to_f64(x) + 1.5 List.map(x, f)}
# ---------------------------------------------------------------------------# Driver: the same as lapply.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(1000000)) seconds <- proc.time()[[3]] - started value <- as.list(List.to_r(result)) text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("lapply %s %.4f\n", checksum, seconds))})lapply with an extra argument lapply-dots 3.33x
Calls a two-argument closure through lapply over 1e6 integers, passing the second argument through ... Source
execute <- function(n=1000000) { x <- 1:n f <- function(x, y) x + 1.5 * y a <- n / 2 lapply(x, f, y=a)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1e6)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("lapply-dots %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> List<F64> { x <- List.range(1, n) f <- function(x: I64, y: F64) -> F64 Num.to_f64(x) + 1.5 * y a <- Num.to_f64(n) / 2 List.map(x, function(x: I64) -> F64 f(x, a))}
# ---------------------------------------------------------------------------# Driver: the same as lapply-dots.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(1000000)) seconds <- proc.time()[[3]] - started value <- as.list(List.to_r(result)) text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("lapply-dots %s %.4f\n", checksum, seconds))})Growing a list, for loop list-for 5.17x
Grows an empty list to 1.5e6 elements by [[<- in a for loop Source
execute <- function(n=500000) { x <- list() for (i in 1:n) { x[[i]] <- i }}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1.5e6)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("list-for %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> NULL { x <- [] for (i in List.range(1, n)) { x <- List.append(x, i) } NULL}
# ---------------------------------------------------------------------------# Driver: the same as list-for.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(1500000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("list-for %s %.4f\n", checksum, seconds))})Growing a list, while loop list-while 5.09x
Grows an empty list to 1.5e6 elements by [[<- in a while loop with a double index Source
execute <- function(n=500000) { x <- list() i <- 1 while (i < n) { x[[i]] <- 5 i <- i + 1 }}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(1.5e6)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("list-while %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> NULL { x <- [] i <- 1 while (i < n) { x <- List.append(x, 5f64) i <- i + 1 } NULL}
# ---------------------------------------------------------------------------# Driver: the same as list-while.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(1500000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("list-while %s %.4f\n", checksum, seconds))})Matrix element assignment matrix-for 3.26x
Assigns every element of a 3,000 x 3,000 matrix with [[i, j]]<- in nested for loops Source
execute <- function(n=2000) { x <- matrix(nrow=n, ncol=n) for (i in 1:n) { for (j in 1:n) { x[[i, j]] <- 5 } }}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(3000)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("matrix-for %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> NULL { x <- List.repeat(0f64, n * n) for (i in List.range(1, n)) { for (j in List.range(1, n)) { x[[(i - 1) * n + j]] <- 5 } } NULL}
# ---------------------------------------------------------------------------# Driver: the same as matrix-for.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(3000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("matrix-for %s %.4f\n", checksum, seconds))})Scalar assignment, for loop scalar-for 12x
Assigns the loop variable to a local in a for loop over 1:5e7 Source
execute <- function(n=100000000) { x <- 0 for (i in 1:n) { x <- i }}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(5e7)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("scalar-for %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> NULL { x: I64 <- 0 for (i in List.range(1, n)) { x <- i } NULL}
# ---------------------------------------------------------------------------# Driver: the same as scalar-for.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(50000000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("scalar-for %s %.4f\n", checksum, seconds))})Scalar assignment, while loop scalar-while 14x
Assigns and increments two double scalars in a while loop, 2.5e7 times Source
execute <- function(n=25000000) { x <- 0 i <- 0 while (i < n) { x <- i i <- i + 1 } c(x, i)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(2.5e7)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("scalar-while %s %.4f\n", checksum, seconds))})execute <- function(n: F64) -> List<F64> { x: F64 <- 0 i: F64 <- 0 while (i < n) { x <- i i <- i + 1 } [x, i]}
# ---------------------------------------------------------------------------# Driver: the same as scalar-while.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(25000000)) seconds <- proc.time()[[3]] - started value <- List.to_r(result) text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("scalar-while %s %.4f\n", checksum, seconds))})Superassignment loop super-while 4.73x
A closure increments a variable of its enclosing function with <<- in a while loop, 6e6 times Source
execute <- function(n=2000000) { x <- 0 f <- function() { while (x < n) { x <<- x + 1 } } f() x}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(6e6)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("super-while %s %.4f\n", checksum, seconds))})execute <- function(n: F64) -> F64 { x <- 0 while (x < n) { x <- x + 1 } x}
# ---------------------------------------------------------------------------# Driver: the same as super-while.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(6000000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("super-while %s %.4f\n", checksum, seconds))})Vector element assignment, for loop vector-for 3.51x
Fills a 3e7-element vector by [[<- in a for loop, the first write coercing it from logical to integer Source
execute <- function(n=15000000) { x <- vector(length=n) for (i in 1:n) { x[[i]] <- i }}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(3e7)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("vector-for %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> NULL { x <- List.repeat(0, n) for (i in List.range(1, n)) { x[[i]] <- i } NULL}
# ---------------------------------------------------------------------------# Driver: the same as vector-for.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- execute(30000000)) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("vector-for %s %.4f\n", checksum, seconds))})Vector element assignment, while loop vector-while 6.90x
Fills a 2e7-element integer vector by [[<- in a while loop with an integer counter, then sums it Source
execute <- function(n=20000000) { x <- integer(length=n) i <- 1L while (i < n) { x[[i]] <- i i <- i + 1L } sum(x)}
# ---------------------------------------------------------------------------# Driver added for ry's `just bench public` (not part of the upstream# file). It runs `execute` once at a fixed size and prints one line:# <name> <checksum of printed output and result> <seconds># Run it from this directory: upstream code reads sibling files by relative path.# The guard skips the driver when another program loads this file for `execute`.if (!exists(".ry_bench_loading")) local({ started <- proc.time()[[3]] output <- capture.output(value <- execute(2e7)) seconds <- proc.time()[[3]] - started text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("vector-while %s %.4f\n", checksum, seconds))})execute <- function(n: I64) -> I64 { x <- List.repeat(0, n) i <- 1 while (i < n) { x[[i]] <- i i <- i + 1 } List.sum(x)}
# ---------------------------------------------------------------------------# Driver: the same as vector-while.R's, except that the R value the checksum reads is# built from the typed result after the clock stops.local({ started <- proc.time()[[3]] output <- capture.output(result <- Num.to_r(execute(20000000))) seconds <- proc.time()[[3]] - started value <- result text <- c(output, capture.output(str(value, vec.len = 3, digits.d = 10, give.attr = FALSE))) bytes <- utf8ToInt(paste(text, collapse = "\n")) checksum <- sprintf("%d:%.0f", length(bytes), sum(as.numeric(bytes) * (seq_along(bytes) %% 251 + 1))) cat(sprintf("vector-while %s %.4f\n", checksum, seconds))})Package test suites
Section titled “Package test suites”This suite times the test suites of packages from ry’s benchmark dependency set. Each package and
every dependency it installs is pinned by version and by the SHA-256 of its source tarball
(tools/bench/packages/lock.tsv), so two machines measure the same code. GNU R installs them into
one library that both engines load, because ry’s libR is ABI-compatible with GNU R’s. The tests
run the way R CMD check runs them, offline. Each time is the wall time of a whole process, or
for a package whose tests/ holds plain scripts, the sum over one process per script, so it
includes start-up and loading the package and its imports, as real use does.
The suite also counts the tests that pass, fail and raise errors on each engine. A package whose counts differ between the engines is flagged, and a package whose tests do not run to the end on an engine is marked as failing there and has no speed-up.
Speed relative to GNU R on a log scale: a bar to the right of 1x is faster than GNU R, to the left slower. The line across a bar spans its 95% interval. A package marked tests differ passed a different number of tests on ry than on GNU R; the flag gives both counts.
Measured on 2026-11-16 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v509; 10 paired rounds.
The numbers: seconds, peak memory and test counts
| program | GNU R | ry | ry, speed-up |
|---|---|---|---|
| abind 1.4-8 | 1.081 s | 0.315 s | 3.35x (3.32x to 3.45x) |
| assertthat 0.2.1 | 1.128 s | 0.303 s | 3.75x (3.39x to 3.87x) |
| brio 1.1.5 | 1.169 s | 0.297 s | 3.82x (3.66x to 3.97x) |
| cachem 1.1.0 | 1.237 s | 0.377 s | 3.30x (3.17x to 3.36x) |
| cli 3.6.6 | 35.056 s | 14.771 s | 2.39x (2.34x to 2.44x) |
| data.table 1.18.6.1 | 51.111 s | 26.577 s | 1.92x (1.88x to 1.93x) |
| DBI 1.3.0 | 1.490 s | 0.440 s | 3.36x (3.16x to 3.50x) |
| digest 0.6.39 | 0.584 s | 0.251 s | 2.28x (2.21x to 2.38x) |
| foreach 1.5.2 | 12.822 s | 10.621 s | 1.21x (1.20x to 1.21x) |
| fs 2.1.0 | 14.347 s | 8.046 s | 1.79x (1.74x to 1.81x) |
| jsonlite 2.0.0 | 4.406 s | 1.760 s | 2.52x (2.45x to 2.60x) |
| lgr 0.5.2 | 9.517 s | 3.364 s | 2.82x (2.75x to 2.87x) |
| lubridate 1.9.5 | 20.956 s | 6.301 s | 3.33x (3.30x to 3.40x) |
| memoise 2.0.1 | 0.992 s | 0.309 s | 3.22x (3.09x to 3.37x) |
| PerformanceAnalytics 2.1.0 | 3.681 s | 1.123 s | 3.23x (3.16x to 3.36x) |
| progress 1.2.3 | 0.794 s | 0.212 s | 3.73x (3.56x to 3.93x) |
| purrr 1.2.2 | 15.826 s | 6.205 s | 2.50x (2.48x to 2.62x) |
| R6 2.6.1 | 4.981 s | 1.280 s | 3.82x (3.70x to 3.94x) |
| rappdirs 0.3.4 | 1.051 s | 0.324 s | 3.19x (3.18x to 3.37x) |
| rlang 1.3.0 | 78.565 s | 27.736 s | 2.81x (2.75x to 2.86x) (tests differ on ry: GNU R: 4016 passed, 0 failed, 0 errors; ry: 3999 passed, 0 failed, 13 errors) |
| snakecase 0.11.1 | 2.490 s | 1.225 s | 2.06x (1.96x to 2.12x) |
| stringr 1.6.0 | 5.522 s | 2.053 s | 2.70x (2.52x to 2.74x) |
| withr 3.0.3 | 4.992 s | 1.978 s | 2.53x (2.47x to 2.60x) (tests differ on ry: GNU R: 358 passed, 0 failed, 0 errors; ry: 357 passed, 0 failed, 0 errors) |
| xts 0.14.3 | 6.411 s | 3.625 s | 1.78x (1.74x to 1.80x) |
| zeallot 0.2.0 | 0.922 s | 0.277 s | 3.31x (3.04x to 3.47x) |
| zoo 1.9-1 | 2.571 s | 0.777 s | 3.37x (3.18x to 3.46x) |
Each time is the median over the rounds. Each speed-up is the median of the per-round ratios, with its 95% interval in parentheses.
| program | GNU R | ry |
|---|---|---|
| abind 1.4-8 | 111 MiB | 93 MiB |
| assertthat 0.2.1 | 112 MiB | 87 MiB |
| brio 1.1.5 | 126 MiB | 95 MiB |
| cachem 1.1.0 | 114 MiB | 88 MiB |
| cli 3.6.6 | 175 MiB | 207 MiB |
| data.table 1.18.6.1 | 438 MiB | 369 MiB |
| DBI 1.3.0 | 123 MiB | 111 MiB |
| digest 0.6.39 | 95 MiB | 87 MiB |
| foreach 1.5.2 | 169 MiB | 123 MiB |
| fs 2.1.0 | 227 MiB | 173 MiB |
| jsonlite 2.0.0 | 155 MiB | 130 MiB |
| lgr 0.5.2 | 154 MiB | 131 MiB |
| lubridate 1.9.5 | 184 MiB | 172 MiB |
| memoise 2.0.1 | 111 MiB | 88 MiB |
| PerformanceAnalytics 2.1.0 | 131 MiB | 130 MiB |
| progress 1.2.3 | 116 MiB | 86 MiB |
| purrr 1.2.2 | 131 MiB | 153 MiB |
| R6 2.6.1 | 116 MiB | 98 MiB |
| rappdirs 0.3.4 | 115 MiB | 96 MiB |
| rlang 1.3.0 | 207 MiB | 223 MiB |
| snakecase 0.11.1 | 120 MiB | 113 MiB |
| stringr 1.6.0 | 128 MiB | 125 MiB |
| withr 3.0.3 | 202 MiB | 142 MiB |
| xts 0.14.3 | 338 MiB | 371 MiB |
| zeallot 0.2.0 | 114 MiB | 89 MiB |
| zoo 1.9-1 | 121 MiB | 103 MiB |
Peak memory is the peak resident set size of the whole process, R's startup included.
| package | GNU R: passed, failed, errors | ry: passed, failed, errors |
|---|---|---|
| abind 1.4-8 | 5, 0, 0 | 5, 0, 0 |
| assertthat 0.2.1 | 159, 0, 0 | 159, 0, 0 |
| brio 1.1.5 | 81, 0, 0 | 81, 0, 0 |
| cachem 1.1.0 | 90, 0, 0 | 90, 0, 0 |
| cli 3.6.6 | 1527, 0, 0 | 1527, 0, 0 |
| data.table 1.18.6.1 | 10, 0, 0 | 10, 0, 0 |
| DBI 1.3.0 | 101, 0, 0 | 101, 0, 0 |
| digest 0.6.39 | 324, 0, 0 | 324, 0, 0 |
| foreach 1.5.2 | 570, 0, 0 | 570, 0, 0 |
| fs 2.1.0 | 3435, 0, 0 | 3435, 0, 0 |
| jsonlite 2.0.0 | 1524, 0, 0 | 1524, 0, 0 |
| lgr 0.5.2 | 541, 0, 0 | 541, 0, 0 |
| lubridate 1.9.5 | 3035, 0, 0 | 3035, 0, 0 |
| memoise 2.0.1 | 160, 0, 0 | 160, 0, 0 |
| PerformanceAnalytics 2.1.0 | 69, 0, 0 | 69, 0, 0 |
| progress 1.2.3 | 17, 0, 0 | 17, 0, 0 |
| purrr 1.2.2 | 735, 0, 0 | 735, 0, 0 |
| R6 2.6.1 | 625, 0, 0 | 625, 0, 0 |
| rappdirs 0.3.4 | 45, 0, 0 | 45, 0, 0 |
| rlang 1.3.0 | 4016, 0, 0 | 3999, 0, 13 |
| snakecase 0.11.1 | 292, 0, 0 | 292, 0, 0 |
| stringr 1.6.0 | 445, 0, 0 | 445, 0, 0 |
| withr 3.0.3 | 358, 0, 0 | 357, 0, 0 |
| xts 0.14.3 | 4038, 0, 0 | 4038, 0, 0 |
| zeallot 0.2.0 | 100, 0, 0 | 100, 0, 0 |
| zoo 1.9-1 | 6, 0, 0 | 6, 0, 0 |
Measured on 2026-11-16 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v509; 10 paired rounds.
| Program | What it runs | ry vs GNU R |
|---|---|---|
abind 1.4-8abind | Combines multidimensional arrays, with scripts that check dimnames and array slicing output | 3.35x |
assertthat 0.2.1assertthat | Easy pre and post assertions, tested through many small predicate calls | 3.75x |
brio 1.1.5brio | Basic R input and output, with tests that read and write files through C code | 3.82x |
cachem 1.1.0cachem | Caches R objects with automatic pruning, in memory and on disk | 3.30x |
cli 3.6.6cli | Helpers for command line interfaces, with snapshot tests of styled and formatted text | 2.39x |
data.table 1.18.6.1data.table | Extension of data.frame, with a large script suite of table operations backed by C code | 1.92x |
DBI 1.3.0DBI | The R database interface, a set of S4 generics, with tests of SQL quoting, interpolation and a dummy driver | 3.36x |
digest 0.6.39digest | Compact hash digests of R objects, with tests that compare many hash algorithms against known values | 2.28x |
foreach 1.5.2foreach | The foreach looping construct, with tests of iterators, result combiners, nesting and error handling | 1.21x |
fs 2.1.0fs | Cross-platform file system operations based on libuv, with tests that create and inspect real files | 1.79x |
jsonlite 2.0.0jsonlite | A JSON parser and generator, with round-trip tests over many R data types | 2.52x |
lgr 0.5.2lgr | A logging framework built on R6 classes, with appenders, layouts and filters | 2.82x |
lubridate 1.9.5lubridate | Date and time handling, with tests of parsing, time zones and period arithmetic | 3.33x |
memoise 2.0.1memoise | Memoisation of functions, with tests of in-memory and file system caches | 3.22x |
PerformanceAnalytics 2.1.0PerformanceAnalytics | Econometric tools for performance and risk analysis of xts return series | 3.23x |
progress 1.2.3progress | Terminal progress bars, with tests of their rendering from R and from C++ | 3.73x |
purrr 1.2.2purrr | Functional programming tools, with tests of map functions and their error handling built on rlang and vctrs | 2.50x |
R6 2.6.1R6 | Encapsulated classes with reference semantics, with tests of inheritance, cloning and active bindings | 3.82x |
rappdirs 0.3.4rappdirs | Determines where to save data, caches and logs, with tests over platform and environment variables | 3.19x |
rlang 1.3.0rlang | Functions for base types and core R features, with a large suite of tests on environments, quosures and conditions | 2.81x |
snakecase 0.11.1snakecase | Converts strings into any case, with tests that run many string transformations | 2.06x |
stringr 1.6.0stringr | Consistent wrappers for common string operations, built on stringi | 2.70x |
withr 3.0.3withr | Runs code with temporarily modified global state, with tests of options, environment variables and on.exit handlers | 2.53x |
xts 0.14.3xts | Extensible time series built on zoo, with tests of merging, subsetting and periodicity | 1.78x |
zeallot 0.2.0zeallot | Multiple, unpacking and destructuring assignment with the %<-% operator | 3.31x |
zoo 1.9-1zoo | S3 infrastructure for regular and irregular time series, with scripts compared against saved output | 3.37x |
Benchmark code bases
Section titled “Benchmark code bases”These are the three synthetic code bases
(finance, data science and biostatistics) of about 300,000 lines in 500 files each, the size of the
code ry is built to run. A program here is one whole code base: ry loads the package with ry load,
GNU R loads it the same way, and each of the code base’s test_that() blocks, about 10,000 per code
base, runs on its own. A code base’s time is the sum of its blocks’ own times, so loading the package
and testthat’s per-file garbage collection are outside it. The result is checked by the number of
blocks that pass, which must agree between the engines.
The suite measures ry with the JIT on and with it off. It is not part of the summary above: the code bases are generated, they depend on the packages of the corpus library, and one round takes about 22 minutes, so the suite runs its 10 rounds without extra rounds for wide intervals.
- ry
- ry, JIT off
finbenchry: 2.17xry, JIT off: 2.19xbiobenchry: 2.05xry, JIT off: 2.04xdsbenchry: 1.94xry, JIT off: 1.96xSpeed relative to GNU R on a log scale: a bar to the right of 1x is faster than GNU R, to the left slower. The line across a bar spans its 95% interval.
Measured on 2026-11-17 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v553; 10 paired rounds.
The numbers: seconds, speed-ups and the speed-up per test
| program | GNU R | ry | ry, JIT off | ry, speed-up | ry, JIT off, speed-up |
|---|---|---|---|---|---|
| Finance | 204.617 s | 100.590 s | 94.436 s | 2.17x (2.05x to 2.18x) | 2.19x (2.14x to 2.21x) |
| Data science | 101.649 s | 52.412 s | 52.588 s | 1.94x (1.92x to 1.97x) | 1.96x (1.91x to 1.99x) |
| Biostatistics | 116.010 s | 57.993 s | 57.376 s | 2.05x (2.01x to 2.10x) | 2.04x (2.00x to 2.10x) |
Each time is the median over the rounds. Each speed-up is the median of the per-round ratios, with its 95% interval in parentheses.
| code base | ry, speed-up per test | ry, JIT off, speed-up per test |
|---|---|---|
| Finance | 2.04x over 9592 of 9592 tests | 2.05x over 9592 of 9592 tests |
| Data science | 1.92x over 9416 of 9416 tests | 1.96x over 9416 of 9416 tests |
| Biostatistics | 2.06x over 8927 of 8927 tests | 2.06x over 8927 of 8927 tests |
Each test block is timed on its own. The speed-up is the geometric mean over the blocks that GNU R runs in 1 ms or more of GNU R's median time over the engine's, so it weighs every test alike, where the Time table weighs the tests by how long they take. The slowest code base against the mean of the suite: ry: Data science at 1.94x; ry, JIT off: Data science at 1.96x.
Measured on 2026-11-17 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v553; 10 paired rounds.
The Per test table gives the geometric mean over the test blocks, so a code base counts every test alike, and the note under it names the slowest code base against the mean.
The corpus library lacks polars, Rblpapi and esgtoolkit, so the code bases run without them.
| Program | What it runs | ry vs GNU R |
|---|---|---|
Financefinbench | pricing, portfolio construction, risk and market-data adapters | 2.17x |
Data sciencedsbench | table pipelines, features, models and serving | 1.94x |
Biostatisticsbiobench | trials, survival, genetics and assay analysis | 2.05x |
Numeric kernels (ours)
Section titled “Numeric kernels (ours)”These are small programs we wrote whose time goes into arithmetic on numbers and numeric vectors:
recursion, scalar loops, element loops over vectors, whole-vector arithmetic and a few kernels from
the finance and biostatistics code bases. A process runs each program once cold and then five
times warm, and the median warm run is its time, so the time leaves out start-up, GNU R’s byte
compilation and ry’s first tier-up. Most programs also exist in typed ry, as a <name>.typed.R
beside the plain R, which runs in strict mode as the ry typed column. Every
engine must print the same checksum as GNU R, or the runner refuses to store the results.
- ry
- ry typed
fibtoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 98xry typed: 140xdrawdowntoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 9.11xry typed: 52xarray_dottoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedwide interval on ry typedwide interval on ry typed, AOTwide interval on ry typed, installedry: 7.49xry typed: 43xarray_maptoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 7.46xry typed: 44xarray_filtertoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 7.24xry typed: 59xloop_sumtoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 6.98xry typed: 21xarray_sumtoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 5.72xry typed: 29xclosurestoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 5.27xry typed: 259xvector_arithtoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 2.97xry typed: 4.08xvasicektoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 2.47xry typed: 3.47xSpeed relative to GNU R on a log scale: a bar to the right of 1x is faster than GNU R, to the left slower. The line across a bar spans its 95% interval. A time marked too short on a ry engine is under 0.1 s. That speed is what the suite measures, so it counts in the geometric mean. A program marked wide interval varied so much between rounds that its ratio's interval is wide; read its median with care.
Measured on 2026-11-17 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v509; 10 paired rounds.
Recursion and scalar loops gain the most from the JIT. Kernels whose time goes into vector and statistical routines gain the least, because those routines run in C on GNU R too. Typed scalar loops and recursion gain more again, because a typed function in strict mode compiles to native code before its first call.
The numbers: seconds and peak memory
| program | GNU R | ry | ry typed | ry typed, AOT | ry typed, installed | ry, speed-up | ry typed, speed-up | ry typed, AOT, speed-up | ry typed, installed, speed-up |
|---|---|---|---|---|---|---|---|---|---|
| Dot product | 0.201 s | 0.027 s | 0.005 s | 0.005 s | 0.005 s | 7.49x (7.11x to 8.03x) (too short on ry) | 43x (37x to 47x) (too short on ry typed, wide interval on ry typed) | 41x (38x to 47x) (too short on ry typed, AOT, wide interval on ry typed, AOT) | 41x (36x to 48x) (too short on ry typed, installed, wide interval on ry typed, installed) |
| Counting filter | 0.145 s | 0.020 s | 0.002 s | 0.003 s | 0.002 s | 7.24x (6.92x to 7.40x) (too short on ry) | 59x (57x to 60x) (too short on ry typed) | 57x (57x to 60x) (too short on ry typed, AOT) | 58x (56x to 61x) (too short on ry typed, installed) |
| Element map | 0.260 s | 0.035 s | 0.006 s | 0.006 s | 0.006 s | 7.46x (7.15x to 7.80x) (too short on ry) | 44x (41x to 45x) (too short on ry typed) | 42x (41x to 43x) (too short on ry typed, AOT) | 42x (40x to 43x) (too short on ry typed, installed) |
| Element sum | 0.435 s | 0.076 s | 0.015 s | 0.015 s | 0.015 s | 5.72x (5.50x to 5.84x) (too short on ry) | 29x (28x to 30x) (too short on ry typed) | 29x (28x to 30x) (too short on ry typed, AOT) | 29x (29x to 30x) (too short on ry typed, installed) |
| Closures and lapply | 0.760 s | 0.142 s | 0.003 s | 0.003 s | 0.003 s | 5.27x (5.08x to 5.45x) | 259x (250x to 269x) (too short on ry typed) | 269x (250x to 275x) (too short on ry typed, AOT) | 264x (258x to 272x) (too short on ry typed, installed) |
| Drawdown and volatility | 0.292 s | 0.032 s | 0.006 s | 0.006 s | 0.005 s | 9.11x (8.97x to 9.32x) (too short on ry) | 52x (50x to 54x) (too short on ry typed) | 50x (48x to 53x) (too short on ry typed, AOT) | 54x (49x to 56x) (too short on ry typed, installed) |
| Recursive Fibonacci | 0.697 s | 0.007 s | 0.005 s | 0.005 s | 0.005 s | 98x (89x to 102x) (too short on ry) | 140x (133x to 143x) (too short on ry typed) | 139x (131x to 142x) (too short on ry typed, AOT) | 140x (134x to 144x) (too short on ry typed, installed) |
| Collatz chains | 0.558 s | 0.040 s | n/a | n/a | n/a | 14x (14x to 14x) (too short on ry) | n/a | n/a | n/a |
| Jackknife estimate | 0.414 s | 0.247 s | n/a | n/a | n/a | 1.65x (1.55x to 1.74x) | n/a | n/a | n/a |
| Log-rank statistic | 0.347 s | 0.218 s | 0.139 s | 0.138 s | 0.141 s | 1.60x (1.58x to 1.62x) | 2.51x (2.42x to 2.55x) | 2.47x (2.42x to 2.52x) | 2.48x (2.46x to 2.51x) |
| Counted loop sum | 0.198 s | 0.029 s | 0.009 s | 0.009 s | 0.007 s | 6.98x (6.81x to 7.11x) (too short on ry) | 21x (20x to 22x) (too short on ry typed) | 22x (21x to 22x) (too short on ry typed, AOT) | 28x (27x to 28x) (too short on ry typed, installed) |
| Pairwise distances | 0.153 s | 0.028 s | n/a | n/a | n/a | 5.67x (5.42x to 5.74x) (too short on ry) | n/a | n/a | n/a |
| Path simulation | 0.449 s | 0.137 s | n/a | n/a | n/a | 3.32x (3.25x to 3.35x) | n/a | n/a | n/a |
| Vasicek rate paths | 0.287 s | 0.119 s | 0.083 s | 0.086 s | 0.083 s | 2.47x (2.34x to 2.55x) | 3.47x (3.33x to 3.62x) (too short on ry typed) | 3.33x (3.18x to 3.56x) (too short on ry typed, AOT) | 3.48x (3.31x to 3.63x) (too short on ry typed, installed) |
| Vector arithmetic | 0.181 s | 0.061 s | 0.045 s | 0.045 s | 0.045 s | 2.97x (2.82x to 3.05x) (too short on ry) | 4.08x (3.83x to 4.16x) (too short on ry typed) | 4.04x (3.86x to 4.13x) (too short on ry typed, AOT) | 4.00x (3.89x to 4.07x) (too short on ry typed, installed) |
| Scale and shift | 0.309 s | 0.037 s | n/a | n/a | n/a | 8.53x (7.97x to 9.00x) (too short on ry) | n/a | n/a | n/a |
Each time is the median over the rounds. Each speed-up is the median of the per-round ratios, with its 95% interval in parentheses. ry typed, AOT compiles each typed function before the program starts, which the First run table shows. ry typed, installed installs the program's definitions as a package, with the machine code of its typed functions in the package's typed code file, and runs the rest of the program from a script that attaches the package. That script is plain R, because ry's checker does not resolve the names `library()` attaches, so each call of the measured function from it converts its arguments at the boundary.
| program | GNU R | ry | ry typed | ry typed, AOT | ry typed, installed | compiled in the session, installed |
|---|---|---|---|---|---|---|
| Dot product | 0.202 s | 0.036 s | 0.007 s | 0.006 s | 0.006 s | 0 |
| Counting filter | 0.149 s | 0.026 s | 0.005 s | 0.004 s | 0.004 s | 0 |
| Element map | 0.274 s | 0.048 s | 0.007 s | 0.006 s | 0.007 s | 0 |
| Element sum | 0.445 s | 0.083 s | 0.018 s | 0.016 s | 0.017 s | 0 |
| Closures and lapply | 0.770 s | 0.155 s | 0.009 s | 0.006 s | 0.006 s | 0 |
| Drawdown and volatility | 0.306 s | 0.050 s | 0.007 s | 0.006 s | 0.006 s | 0 |
| Recursive Fibonacci | 0.720 s | 0.009 s | 0.006 s | 0.005 s | 0.005 s | 0 |
| Collatz chains | 0.621 s | 0.045 s | n/a | n/a | n/a | n/a |
| Jackknife estimate | 0.471 s | 0.250 s | n/a | n/a | n/a | n/a |
| Log-rank statistic | 0.395 s | 0.239 s | 0.141 s | 0.143 s | 0.139 s | 0 |
| Counted loop sum | 0.201 s | 0.032 s | 0.010 s | 0.009 s | 0.007 s | 0 |
| Pairwise distances | 0.168 s | 0.037 s | n/a | n/a | n/a | n/a |
| Path simulation | 0.497 s | 0.171 s | n/a | n/a | n/a | n/a |
| Vasicek rate paths | 0.318 s | 0.134 s | 0.086 s | 0.087 s | 0.086 s | 0 |
| Vector arithmetic | 0.229 s | 0.070 s | 0.047 s | 0.046 s | 0.046 s | 0 |
| Scale and shift | 0.353 s | 0.049 s | n/a | n/a | n/a | n/a |
The first run of the program in its process, as the median over the rounds. It holds whatever compiles at a first call, which the warm runs of the Time table do not. ry typed, AOT compiled the program before it started, so its first run compiles nothing. ry typed, installed runs the code compiled at install, and the last column counts the functions its package's typed code file left out, which compile in the session.
| program | GNU R | ry | ry typed | ry typed, AOT | ry typed, installed |
|---|---|---|---|---|---|
| Dot product | 100 MiB | 81 MiB | 80 MiB | 78 MiB | 85 MiB |
| Counting filter | 100 MiB | 77 MiB | 80 MiB | 81 MiB | 83 MiB |
| Element map | 123 MiB | 98 MiB | 77 MiB | 81 MiB | 83 MiB |
| Element sum | 100 MiB | 80 MiB | 77 MiB | 78 MiB | 83 MiB |
| Closures and lapply | 138 MiB | 111 MiB | 56 MiB | 56 MiB | 59 MiB |
| Drawdown and volatility | 92 MiB | 90 MiB | 97 MiB | 97 MiB | 102 MiB |
| Recursive Fibonacci | 69 MiB | 50 MiB | 51 MiB | 49 MiB | 57 MiB |
| Collatz chains | 70 MiB | 51 MiB | n/a | n/a | n/a |
| Jackknife estimate | 124 MiB | 52 MiB | n/a | n/a | n/a |
| Log-rank statistic | 126 MiB | 80 MiB | 60 MiB | 64 MiB | 63 MiB |
| Counted loop sum | 69 MiB | 49 MiB | 51 MiB | 52 MiB | 55 MiB |
| Pairwise distances | 70 MiB | 57 MiB | n/a | n/a | n/a |
| Path simulation | 172 MiB | 147 MiB | n/a | n/a | n/a |
| Vasicek rate paths | 160 MiB | 90 MiB | 90 MiB | 90 MiB | 86 MiB |
| Vector arithmetic | 138 MiB | 73 MiB | 77 MiB | 78 MiB | 86 MiB |
| Scale and shift | 171 MiB | 152 MiB | n/a | n/a | n/a |
Peak memory is the peak resident set size of the whole process, R's startup included.
Measured on 2026-11-17 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v509; 10 paired rounds.
The programs
Section titled “The programs”Each program as plain R and, where it exists, typed. The number beside the name is ry’s speed-up on the plain R.
Dot product array_dot 7.49x
An element loop over a million doubles summing `x[[i]] * y[[i]]`, five times: scalar indexing and arithmetic. Source
array_dot <- function(x, y, times) { total <- 0 n <- length(x) for (k in seq_len(times)) { for (i in seq_len(n)) total <- total + x[[i]] * y[[i]] } total}x <- seq(0, 1, length.out = 1000000L)y <- rev(x)measure("array_dot", function() array_dot(x, y, 5L))array_dot <- function(x: List<F64>, y: List<F64>, times: I64) -> F64 { total: F64 <- 0 n <- List.len(x) for (k in List.range(1, times)) { for (i in List.range(1, n)) total <- total + x[[i]] * y[[i]] } total}x <- List.from_r(seq(0, 1, length.out = 1000000L))y <- List.reverse(x)measure("array_dot", function() array_dot(x, y, 5))Counting filter array_filter 7.24x
An element loop over a million doubles counting those above one half: indexing and comparison in a loop. The typed program counts with `List.count_if`. Source
array_filter <- function(x, y, times) { total <- 0 n <- length(x) for (k in seq_len(times)) { for (i in seq_len(n)) if (x[[i]] > 0.5) total <- total + 1 } total}x <- seq(0, 1, length.out = 1000000L)y <- rev(x)measure("array_filter", function() array_filter(x, y, 5L))array_filter <- function(x: List<F64>, times: I64) -> F64 { total: F64 <- 0 for (k in List.range(1, times)) { total <- total + Num.to_f64(List.count_if(x, function(item: F64) -> Bool item > 0.5)) } total}x <- List.from_r(seq(0, 1, length.out = 1000000L))measure("array_filter", function() array_filter(x, 5))Element map array_map 7.46x
An element loop writing `x[[i]] * 2 + 1` into a preallocated vector of a million doubles: subassignment in a loop. Source
array_map <- function(x, y, times) { total <- 0 n <- length(x) out <- numeric(n) for (k in seq_len(times)) { for (i in seq_len(n)) out[[i]] <- x[[i]] * 2 + 1 total <- total + sum(out) } total}x <- seq(0, 1, length.out = 1000000L)y <- rev(x)measure("array_map", function() array_map(x, y, 5L))array_map <- function(x: List<F64>, times: I64) -> F64 { total <- 0 for (k in List.range(1, times)) total <- total + List.sum(x * 2 + 1) total}x <- List.from_r(seq(0, 1, length.out = 1000000L))measure("array_map", function() array_map(x, 5))Element sum array_sum 5.72x
An element loop summing a million doubles, twenty times: the cheapest indexed loop. Source
array_sum <- function(x, y, times) { total <- 0 n <- length(x) for (k in seq_len(times)) { for (i in seq_len(n)) total <- total + x[[i]] } total}x <- seq(0, 1, length.out = 1000000L)y <- rev(x)measure("array_sum", function() array_sum(x, y, 20L))array_sum <- function(x: List<F64>, times: I64) -> F64 { total: F64 <- 0 for (k in List.range(1, times)) { for (item in x) total <- total + item } total}x <- List.from_r(seq(0, 1, length.out = 1000000L))measure("array_sum", function() array_sum(x, 20))Closures and lapply closures 5.27x
Small closures called in a loop, then lapply and vapply over a sequence: closure calls and argument matching. Source
closures <- function(n) { add <- function(a, b) a + b scale <- 3 times_scale <- function(a) a * scale s <- 0 for (i in 1:n) s <- add(s, times_scale(i)) squares <- lapply(seq_len(n), function(x) x * (x + 0.5)) halves <- vapply(seq_len(n), function(x) x / 2, numeric(1)) squared <- unlist(squares) s + sum(squared) + sum(halves)}measure("closures", function() closures(300000L))closures <- function(n: I64) -> F64 { add <- function(a: F64, b: F64) -> F64 a + b scale <- 3 times_scale <- function(a: F64) -> F64 a * scale s: F64 <- 0 for (i in List.range(1, n)) s <- add(s, times_scale(Num.to_f64(i))) squares <- List.map(List.range(1, n), function(x: I64) -> F64 Num.to_f64(x) * (Num.to_f64(x) + 0.5)) halves <- List.map(List.range(1, n), function(x: I64) -> F64 Num.to_f64(x) / 2) s + List.sum(squares) + List.sum(halves)}measure("closures", function() closures(300000))Drawdown and volatility drawdown 9.11x
Maximum drawdown and EWMA volatility in one pass over a return series: scalar state carried through a loop. Source
risk_report <- function(returns, lambda = 0.94) { wealth <- 1 peak <- 1 worst <- 0 variance <- returns[1] * returns[1] for (i in seq_along(returns)) { r <- returns[i] wealth <- wealth * (1 + r) if (wealth > peak) peak <- wealth drawdown <- (peak - wealth) / peak if (drawdown > worst) worst <- drawdown variance <- lambda * variance + (1 - lambda) * r * r } c(max_drawdown = worst, volatility = sqrt(variance * 252))}returns <- sin(seq_len(2000000L) * 0.37) * 0.01 + 0.0002measure("drawdown", function() sum(risk_report(returns)))risk_report <- function(returns: List<F64>, lambda: F64 = 0.94) -> F64 { wealth <- 1 peak <- 1 worst <- 0 first <- returns[[1]] variance <- first * first for (r in returns) { wealth <- wealth * (1 + r) if (wealth > peak) peak <- wealth drawdown <- (peak - wealth) / peak if (drawdown > worst) worst <- drawdown variance <- lambda * variance + (1 - lambda) * r * r } worst + Num.sqrt(variance * 252)}returns <- List.from_r(sin(seq_len(2000000L) * 0.37) * 0.01 + 0.0002)measure("drawdown", function() risk_report(returns))Recursive Fibonacci fib 98x
fib(30), about 2.7 million calls of a small recursive function: call overhead. Source
fib <- function(n) if (n < 2) n else fib(n - 1) + fib(n - 2)measure("fib", function() fib(30))fib <- function(n: I64) -> I64 if (n < 2) n else fib(n - 1) + fib(n - 2)measure("fib", function() Num.to_f64(fib(30)))Collatz chains integer_loop 14x
Collatz chain lengths up to 30,000 in nested while loops: integer arithmetic and branches. Source
Jackknife estimate jackknife 1.65x
A jackknife standard error through vapply and a closure that drops one element: vector copies per call. Source
Log-rank statistic log_rank 1.60x
The log-rank test statistic, a loop over event times with whole-vector comparisons in its body. Source
log_rank <- function(data) { times <- sort(unique(data$time[data$event == 1L])) observed <- 0 expected <- 0 variance <- 0 for (t in times) { risk <- data$time >= t n <- sum(risk) n1 <- sum(risk & data$arm == "treated") d <- sum(data$time == t & data$event == 1L) d1 <- sum(data$time == t & data$event == 1L & data$arm == "treated") observed <- observed + d1 expected <- expected + d * n1 / n if (n > 1) variance <- variance + d * (n1 / n) * (1 - n1 / n) * (n - d) / (n - 1) } (observed - expected)^2 / variance}subjects <- 16000Ldata <- list( time = (seq_len(subjects) * 7919L) %% 1000L + 1L, event = as.integer(seq_len(subjects) %% 3L != 0L), arm = ifelse(seq_len(subjects) %% 2L == 0L, "treated", "control"))measure("log_rank", function() log_rank(data))log_rank <- function(time: List<I64>, event: List<Bool>, treated: List<Bool>) -> F64 { count <- function(mask: List<Bool>) -> F64 Num.to_f64(List.count_if(mask, function(b) b)) times <- List.sort_asc(Set.to_list(Set.from_list(time[event]))) observed <- 0 expected <- 0 variance <- 0 for (t in times) { risk <- time >= t died <- time == t & event n <- count(risk) n1 <- count(risk & treated) d <- count(died) d1 <- count(died & treated) observed <- observed + d1 expected <- expected + d * n1 / n if (n > 1) variance <- variance + d * (n1 / n) * (1 - n1 / n) * (n - d) / (n - 1) } (observed - expected) * (observed - expected) / variance}subjects <- List.range(1, 16000)time <- List.map(subjects, function(i) (i * 7919) %% 1000 + 1)event <- List.map(subjects, function(i) i %% 3 != 0)treated <- List.map(subjects, function(i) i %% 2 == 0)measure("log_rank", function() log_rank(time, event, treated))Counted loop sum loop_sum 6.98x
A scalar double accumulator in a counted loop of ten million steps: the bare loop. Source
loop_sum <- function(n) { s <- 0 for (i in 1:n) s <- s + i * 0.5 s}measure("loop_sum", function() loop_sum(10000000L))loop_sum <- function(n: I64) -> F64 { s <- 0 for (i in List.range(1, n)) s <- s + Num.to_f64(i) * 0.5 s}measure("loop_sum", function() loop_sum(10000000))Pairwise distances nested_loops 5.67x
An O(n^2) pairwise distance sum in two nested loops: scalar indexing in an inner loop. Source
Path simulation simulation 3.32x
Simulated price paths with matrix products, apply over rows, quantiles and sorting: vectorized model code. Source
Vasicek rate paths vasicek 2.47x
Vasicek interest-rate paths, one matrix row per step: vector arithmetic and matrix subassignment. Source
vasicek_paths <- function(paths = 200L, steps = 20000L, r0 = 0.03, kappa = 0.5, theta = 0.04, sigma = 0.01, dt = 1 / 12, seed = 9L) { set.seed(seed) rates <- matrix(r0, nrow = steps + 1L, ncol = paths) for (t in seq_len(steps)) { shock <- stats::rnorm(paths) previous <- rates[t, ] rates[t + 1L, ] <- previous + kappa * (theta - previous) * dt + sigma * sqrt(dt) * shock } rates}measure("vasicek", function() sum(vasicek_paths()))vasicek <- function(paths: I64 = 200, steps: I64 = 20000, r0: F64 = 0.03, kappa: F64 = 0.5, theta: F64 = 0.04, sigma: F64 = 0.01, dt: F64 = 1f64 / 12f64, seed: I64 = 9) -> F64 { set.seed(Num.to_r(seed)) rates <- List.repeat(r0, paths) total <- List.sum(rates) for (t in List.range(1, steps)) { shock <- List.from_r(stats::rnorm(Num.to_r(paths))) rates <- rates + kappa * (theta - rates) * dt + sigma * Num.sqrt(dt) * shock total <- total + List.sum(rates) } total}measure("vasicek", function() vasicek())Vector arithmetic vector_arith 2.97x
Whole-vector arithmetic on a million doubles, repeated in a loop: allocation of large temporaries. Source
vector_arith <- function(x, times) { total <- 0 for (k in seq_len(times)) { y <- x * 2 + x / 3 - 1 total <- total + sum(y) } total}x <- seq(0, 1, length.out = 1000000L)measure("vector_arith", function() vector_arith(x, 20L))vector_arith <- function(x: List<F64>, times: I64) -> F64 { total <- 0 for (k in List.range(1, times)) total <- total + List.sum(x * 2 + x / 3 - 1) total}x <- List.from_r(seq(0, 1, length.out = 1000000L))measure("vector_arith", function() vector_arith(x, 20))Scale and shift vector_loop 8.53x
Element-wise reads and writes of a double vector in a loop: `y[i] <- x[i] * 2 + 1`. Source
Every program reports its time through harness.R, which also prints the checksum that all engines must agree on.
Application workloads (ours)
Section titled “Application workloads (ours)”These are programs we wrote in the shape of the code that packages and analyses run: validation at API boundaries, condition handling, S3, S4 and R6 objects, records as named lists, string building, data frames and data.table, time series and a testthat suite. Their time goes into R’s object and data machinery rather than into arithmetic. They are measured like the kernels, and six of them also exist in typed ry.
- ry
- ry typed
reporttoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 15xry typed: 112xorderstoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 6.79xry typed: 531xbond_booktoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 3.49xry typed: 25xsalestoo short on rytoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 3.16xry typed: 6.88xteam_scorestoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 2.85xry typed: 213xexpr_treetoo short on ry typedtoo short on ry typed, AOTtoo short on ry typed, installedry: 2.22xry typed: 62xSpeed relative to GNU R on a log scale: a bar to the right of 1x is faster than GNU R, to the left slower. The line across a bar spans its 95% interval. A time marked too short on a ry engine is under 0.1 s. That speed is what the suite measures, so it counts in the geometric mean.
Measured on 2026-11-17 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v509; 10 paired rounds.
These programs gain less than the kernels, because call setup, method dispatch, condition handling and complex assignment decide their time, not loops the JIT compiles. Typing gains the most where the typed core compiles the whole program. Where it refuses part of a program, that part runs in the interpreter, and the flag under the bar names what was refused.
The numbers: seconds and peak memory
| program | GNU R | ry | ry typed | ry typed, AOT | ry typed, installed | ry, speed-up | ry typed, speed-up | ry typed, AOT, speed-up | ry typed, installed, speed-up |
|---|---|---|---|---|---|---|---|---|---|
| Bond book pricing | 0.589 s | 0.168 s | 0.023 s | 0.023 s | 0.021 s | 3.49x (3.34x to 3.65x) | 25x (24x to 26x) (too short on ry typed) | 26x (25x to 27x) (too short on ry typed, AOT) | 29x (28x to 29x) (too short on ry typed, installed) |
| Condition handling | 0.570 s | 0.255 s | n/a | n/a | n/a | 2.21x (2.06x to 2.29x) | n/a | n/a | n/a |
| Expression tree | 0.315 s | 0.141 s | 0.005 s | 0.005 s | 0.005 s | 2.22x (2.17x to 2.27x) | 62x (58x to 66x) (too short on ry typed) | 62x (58x to 67x) (too short on ry typed, AOT) | 67x (62x to 69x) (too short on ry typed, installed) |
| Functional style | 0.684 s | 0.264 s | n/a | n/a | n/a | 2.62x (2.55x to 2.66x) | n/a | n/a | n/a |
| Object systems | 0.788 s | 0.236 s | n/a | n/a | n/a | 3.30x (3.21x to 3.41x) | n/a | n/a | n/a |
| Order invoicing | 0.637 s | 0.092 s | 0.001 s | 0.001 s | 0.001 s | 6.79x (6.62x to 6.96x) (too short on ry) | 531x (527x to 540x) (too short on ry typed) | 532x (518x to 547x) (too short on ry typed, AOT) | 555x (541x to 563x) (too short on ry typed, installed) |
| Records as lists | 0.503 s | 0.155 s | n/a | n/a | n/a | 3.30x (3.06x to 3.36x) | n/a | n/a | n/a |
| Report formatting | 0.602 s | 0.040 s | 0.005 s | 0.005 s | 0.005 s | 15x (15x to 16x) (too short on ry) | 112x (109x to 116x) (too short on ry typed) | 111x (107x to 117x) (too short on ry typed, AOT) | 112x (104x to 116x) (too short on ry typed, installed) |
| Sales table pipeline | 0.117 s | 0.037 s | 0.017 s | 0.017 s | 0.017 s | 3.16x (2.97x to 3.22x) (too short on ry) | 6.88x (6.34x to 7.26x) (too short on ry typed) | 7.04x (6.70x to 7.22x) (too short on ry typed, AOT) | 7.07x (6.78x to 7.35x) (too short on ry typed, installed) |
| String handling | 0.744 s | 0.084 s | n/a | n/a | n/a | 8.96x (8.37x to 9.14x) (too short on ry) | n/a | n/a | n/a |
| Tables | 0.373 s | 0.203 s | n/a | n/a | n/a | 1.82x (1.76x to 1.90x) | n/a | n/a | n/a |
| Row validation | 0.818 s | 0.281 s | 0.004 s | 0.004 s | 0.004 s | 2.85x (2.79x to 3.00x) | 213x (207x to 218x) (too short on ry typed) | 211x (207x to 218x) (too short on ry typed, AOT) | 206x (202x to 212x) (too short on ry typed, installed) |
| testthat suite | 0.651 s | 0.120 s | n/a | n/a | n/a | 5.33x (5.15x to 5.62x) | n/a | n/a | n/a |
| Time series and dates | 1.228 s | 0.587 s | n/a | n/a | n/a | 2.09x (2.07x to 2.14x) | n/a | n/a | n/a |
| Argument validation | 0.819 s | 0.152 s | n/a | n/a | n/a | 5.33x (5.11x to 5.47x) | n/a | n/a | n/a |
Each time is the median over the rounds. Each speed-up is the median of the per-round ratios, with its 95% interval in parentheses. ry typed, AOT compiles each typed function before the program starts, which the First run table shows. ry typed, installed installs the program's definitions as a package, with the machine code of its typed functions in the package's typed code file, and runs the rest of the program from a script that attaches the package. That script is plain R, because ry's checker does not resolve the names `library()` attaches, so each call of the measured function from it converts its arguments at the boundary.
| program | GNU R | ry | ry typed | ry typed, AOT | ry typed, installed | compiled in the session, installed |
|---|---|---|---|---|---|---|
| Bond book pricing | 0.627 s | 0.181 s | 0.024 s | 0.023 s | 0.021 s | 0 |
| Condition handling | 0.631 s | 0.266 s | n/a | n/a | n/a | n/a |
| Expression tree | 0.313 s | 0.141 s | 0.008 s | 0.007 s | 0.007 s | 0 |
| Functional style | 0.984 s | 0.306 s | n/a | n/a | n/a | n/a |
| Object systems | 0.935 s | 0.230 s | n/a | n/a | n/a | n/a |
| Order invoicing | 0.670 s | 0.119 s | 0.003 s | 0.001 s | 0.001 s | 0 |
| Records as lists | 0.601 s | 0.171 s | n/a | n/a | n/a | n/a |
| Report formatting | 0.573 s | 0.040 s | 0.011 s | 0.006 s | 0.006 s | 0 |
| Sales table pipeline | 0.189 s | 0.054 s | 0.028 s | 0.024 s | 0.025 s | 0 |
| String handling | 0.972 s | 0.149 s | n/a | n/a | n/a | n/a |
| Tables | 0.402 s | 0.249 s | n/a | n/a | n/a | n/a |
| Row validation | 0.851 s | 0.292 s | 0.010 s | 0.005 s | 0.006 s | 0 |
| testthat suite | 0.832 s | 0.153 s | n/a | n/a | n/a | n/a |
| Time series and dates | 1.317 s | 0.643 s | n/a | n/a | n/a | n/a |
| Argument validation | 0.882 s | 0.158 s | n/a | n/a | n/a | n/a |
The first run of the program in its process, as the median over the rounds. It holds whatever compiles at a first call, which the warm runs of the Time table do not. ry typed, AOT compiled the program before it started, so its first run compiles nothing. ry typed, installed runs the code compiled at install, and the last column counts the functions its package's typed code file left out, which compile in the session.
| program | GNU R | ry | ry typed | ry typed, AOT | ry typed, installed |
|---|---|---|---|---|---|
| Bond book pricing | 70 MiB | 65 MiB | 52 MiB | 53 MiB | 58 MiB |
| Condition handling | 70 MiB | 69 MiB | n/a | n/a | n/a |
| Expression tree | 184 MiB | 160 MiB | 71 MiB | 73 MiB | 74 MiB |
| Functional style | 121 MiB | 110 MiB | n/a | n/a | n/a |
| Object systems | 82 MiB | 94 MiB | n/a | n/a | n/a |
| Order invoicing | 70 MiB | 68 MiB | 53 MiB | 53 MiB | 56 MiB |
| Records as lists | 148 MiB | 119 MiB | n/a | n/a | n/a |
| Report formatting | 73 MiB | 66 MiB | 60 MiB | 60 MiB | 60 MiB |
| Sales table pipeline | 182 MiB | 154 MiB | 120 MiB | 120 MiB | 125 MiB |
| String handling | 107 MiB | 103 MiB | n/a | n/a | n/a |
| Tables | 96 MiB | 139 MiB | n/a | n/a | n/a |
| Row validation | 123 MiB | 125 MiB | 76 MiB | 73 MiB | 76 MiB |
| testthat suite | 100 MiB | 89 MiB | n/a | n/a | n/a |
| Time series and dates | 122 MiB | 125 MiB | n/a | n/a | n/a |
| Argument validation | 70 MiB | 68 MiB | n/a | n/a | n/a |
Peak memory is the peak resident set size of the whole process, R's startup included.
Measured on 2026-11-17 on the ry 0.5.0 release archive (sha256 575ad8ad890b) with GNU R 4.6.2 on Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, Linux 6.18.44-fc-v509; 10 paired rounds.
Bond book pricing bond_book 3.49x
Prices 200,000 bonds, each a short vector computation through seq_len, rep, exp and sum: many small base calls. Source
bond_price <- function(coupon, rate, years) { times <- seq_len(years) flows <- rep(coupon, years) flows[[years]] <- flows[[years]] + 100 sum(flows * exp(-rate * times))}price_book <- function(n) { total <- 0 for (i in seq_len(n)) { total <- total + bond_price(2 + i %% 5L, 0.01 + (i %% 7L) * 0.003, 5L + i %% 20L) } round(total, 6)}measure("bond_book", function() price_book(200000L))bond_price <- function(coupon: F64, rate: F64, years: I64) -> F64 { List.walk(List.range(1, years), 0, function(total, year) { flow <- if (year == years) coupon + 100 else coupon total + flow * Num.exp(-rate * Num.to_f64(year)) })}price_book <- function(n: I64) -> F64 { total <- 0 for (i in List.range(1, n)) { total <- total + bond_price(Num.to_f64(2 + i %% 5), 0.01 + Num.to_f64(i %% 7) * 0.003, 5 + i %% 20) } Num.to_f64(Num.round(total * 1000000)) / 1000000}measure("bond_book", function() price_book(200000))Condition handling conditions 2.21x
tryCatch, withCallingHandlers, custom condition classes, retries and on.exit around fallible steps. Source
Expression tree expr_tree 2.22x
Builds and evaluates a tree of sums, maxima and negations: recursion over nested lists. Source
build <- function(depth, seed) { if (depth == 0L) return(list(kind = "num", value = seed %% 10L + 1)) left <- build(depth - 1L, (seed * 7L) %% 1009L + 1L) if (seed %% 5L == 0L) return(list(kind = "neg", inner = left)) right <- build(depth - 1L, (seed * 13L) %% 1013L + 3L) if (seed %% 2L == 0L) list(kind = "add", left = left, right = right) else list(kind = "max", left = left, right = right)}evaluate <- function(node) { switch(node$kind, num = node$value, neg = -evaluate(node$inner), add = evaluate(node$left) + evaluate(node$right), max = max(evaluate(node$left), evaluate(node$right)) )}tree <- build(21L, 5L)measure("expr_tree", function() evaluate(tree) + evaluate(build(14L, 8L)))type Node = :Num(value: F64) | :Neg(inner: Node) | :Add(left: Node, right: Node) | :Max(left: Node, right: Node)
build <- function(depth: I64, seed: I64) -> Node { if (depth == 0) return(@Node(:Num(value = Num.to_f64(seed %% 10 + 1)))) left <- build(depth - 1, (seed * 7) %% 1009 + 1) if (seed %% 5 == 0) return(@Node(:Neg(inner = left))) right <- build(depth - 1, (seed * 13) %% 1013 + 3) if (seed %% 2 == 0) @Node(:Add(left = left, right = right)) else @Node(:Max(left = left, right = right))}evaluate <- function(node: Node) -> F64 { match (node) { :Num(value = v) => v :Neg(inner = e) => -evaluate(e) :Add(left = a, right = b) => evaluate(a) + evaluate(b) :Max(left = a, right = b) => Num.max(evaluate(a), evaluate(b)) }}tree <- build(21, 5)measure("expr_tree", function() { small <- build(14, 8) evaluate(tree) + evaluate(small)})Functional style functional 2.62x
lapply, Map, Filter, Reduce, do.call and purrr over lists, function factories and memoization in an environment. Source
Object systems objects 3.30x
S3 methods with UseMethod and NextMethod, S4 classes with validity, R6 classes with active bindings. Source
Order invoicing orders 6.79x
Prices order lines with a loyalty discount and regional tax, then totals invoices: records and branches. Source
price_line <- function(order, rates) { net <- order$quantity * order$unit if (order$loyal) net <- net * 0.95 if (order$quantity > 5L) net <- net - 1 tax <- net * rates[[order$region]] list(id = order$id, net = net, tax = tax, gross = net + tax)}price_orders <- function(n) { regions <- c("north", "south", "east", "west") rates <- c(north = 0.2, south = 0.1, east = 0.15, west = 0.05) total <- 0 for (i in seq_len(n)) { order <- list(id = i, quantity = i %% 7L + 1L, unit = 10 + (i %% 13L) * 0.5, loyal = i %% 3L == 0L, region = regions[[i %% 4L + 1L]]) invoice <- price_line(order, rates) total <- total + invoice$gross } total}measure("orders", function() price_orders(200000L))alias Region = :North | :South | :East | :Westalias Order = Record{id: I64, quantity: I64, unit: F64, loyal: Bool, region: Region}alias Invoice = Record{id: I64, net: F64, tax: F64, gross: F64}
tax_rate <- function(region: Region) -> F64 { match (region) { :North => 0.2 :South => 0.1 :East => 0.15 :West => 0.05 }}price_line <- function(order: Order) -> Invoice { net <- Num.to_f64(order$quantity) * order$unit if (order$loyal) net <- net * 0.95 if (order$quantity > 5) net <- net - 1 tax <- net * tax_rate(order$region) (id = order$id, net = net, tax = tax, gross = net + tax)}region_of <- function(i: I64) -> Region { k <- i %% 4 if (k == 0) :North else if (k == 1) :South else if (k == 2) :East else :West}price_orders <- function(n: I64) -> F64 { total <- 0 for (i in List.range(1, n)) { order <- (id = i, quantity = i %% 7 + 1, unit = 10 + Num.to_f64(i %% 13) * 0.5, loyal = i %% 3 == 0, region = region_of(i)) invoice <- price_line(order) total <- total + invoice$gross } total}measure("orders", function() price_orders(200000))Records as lists records 3.30x
Named lists grown, updated with `$<-` and `[[<-`, merged with modifyList, grouped with split and bound with rbind. Source
Report formatting report 15x
Formats one line per account, then joins and measures the report: string building. Source
report <- function(n) { lines <- character(n) for (i in seq_len(n)) { name <- paste0("ACC", formatC(i, width = 6L, flag = "0")) side <- if (i %% 2L == 0L) "long" else "short" lines[[i]] <- paste(name, sprintf("%.2f", i * 1.25), side, sep = ";") } text <- paste(lines, collapse = "\n") nchar(text) + sum(nchar(toupper(lines)) > 25L) + sum(startsWith(lines, "ACC00"))}measure("report", function() report(20000L))report <- function(n: I64) -> F64 { padded <- function(digits: Str, width: I64) -> Str Str.concat(Str.repeat("0", width - Str.count_utf8_bytes(digits)), digits) lines <- List.map(List.range(1, n), function(i: I64) -> Str { cents <- i * 125 amount <- f"{cents %/% 100}.{padded(Num.to_str(cents %% 100), 2)}" side <- if (i %% 2 == 0) "long" else "short" f"ACC{padded(Num.to_str(i), 6)};{amount};{side}" }) text <- Str.join_with(lines, "\n") long <- List.count_if(lines, function(line) Str.count_utf8_bytes(Str.with_ascii_uppercased(line)) > 25) early <- List.count_if(lines, function(line) Str.starts_with(line, "ACC00")) Num.to_f64(Str.count_utf8_bytes(text) + long + early)}measure("report", function() report(20000))Sales table pipeline sales 3.16x
Filters a million sales rows, adds a revenue column and totals it per region: data frame indexing and tapply. Source
pipeline <- function(sales) { big <- sales[sales$units > 3L, ] big$revenue <- big$units * big$price totals <- tapply(big$revenue, big$region, sum) sum(totals * seq_along(totals))}i <- seq_len(1000000L)sales <- data.frame(region = c("north", "south", "east", "west")[i %% 4L + 1L], units = i %% 17L, price = 1 + i %% 100L)measure("sales", function() pipeline(sales))pipeline <- function(region: List<Str>, units: List<I64>, price: List<F64>) -> F64 { totals <- Dict.empty() for (k in List.range(1, List.len(units))) { if (units[[k]] > 3) { revenue <- Num.to_f64(units[[k]]) * price[[k]] totals <- Dict.update(totals, region[[k]], function(found: Result<F64, :Missing>) -> Result<F64, :Missing> :Ok(Result.with_default(found, 0) + revenue)) } } total <- function(name: Str) -> F64 Result.with_default(Dict.get(totals, name), 0) total("east") + 2 * total("north") + 3 * total("south") + 4 * total("west")}i <- seq_len(1000000L)region <- List.from_r(c("north", "south", "east", "west")[i %% 4L + 1L])units <- List.from_r(i %% 17L)price <- List.from_r(1 + i %% 100L)measure("sales", function() pipeline(region, units, price))String handling strings 8.96x
paste, sprintf, gsub, regmatches, splitting and padding, and the same through stringr. Source
Tables tables 1.82x
data.table grouping, `:=` updates, keyed joins and rbindlist, and the same steps on base data frames. Source
Row validation team_scores 2.85x
Parses comma-separated rows, rejects invalid ones and totals scores per team: strsplit, conversion and failures as values. Source
parse_row <- function(row) { parts <- strsplit(row, ",", fixed = TRUE)[[1L]] age <- suppressWarnings(as.integer(parts[[2L]])) if (is.na(age)) return(list(ok = FALSE, error = "bad_age")) if (age < 18L) return(list(ok = FALSE, error = "minor")) list(ok = TRUE, value = list(name = parts[[1L]], age = age, score = as.double(parts[[3L]]), team = parts[[4L]]))}team_scores <- function(rows) { parsed <- lapply(rows, parse_row) totals <- list() errors <- 0L for (p in parsed) { if (p$ok) { team <- p$value$team old <- totals[[team]] totals[[team]] <- (if (is.null(old)) 0 else old) + p$value$score } else { errors <- errors + 1L } } totals[["red"]] + 2 * totals[["blue"]] + 3 * totals[["green"]] + errors}i <- seq_len(60000L)rows <- paste0("user", i, ",", ifelse(i %% 17L == 0L, "x", as.character(i %% 90L)), ",", (i %% 50L) / 2, ",", c("red", "blue", "green")[i %% 3L + 1L])measure("team_scores", function() team_scores(rows))alias Person = Record{name: Str, age: I64, score: F64, team: Str}
parse_row <- function(row: Str) -> Result<Person, :BadAge | :BadScore | :Minor> { parts <- Str.split_on(row, ",") match (Str.to_i64(parts[[2]])) { :Err(_) => :Err(:BadAge) :Ok(age) => if (age < 18) :Err(:Minor) else match (Str.to_f64(parts[[3]])) { :Err(_) => :Err(:BadScore) :Ok(score) => :Ok((name = parts[[1]], age = age, score = score, team = parts[[4]])) } }}team_scores <- function(rows: List<Str>) -> F64 { parsed <- List.map(rows, parse_row) people <- List.keep_oks(parsed, function(p: Result<Person, :BadAge | :BadScore | :Minor>) -> Result<Person, :BadAge | :BadScore | :Minor> p) totals <- List.walk(people, Dict.empty(), function(seen: Dict<Str, F64>, person: Person) -> Dict<Str, F64> { Dict.update(seen, person$team, function(found: Result<F64, :Missing>) -> Result<F64, :Missing> :Ok(Result.with_default(found, 0) + person$score)) }) errors <- Num.to_f64(List.len(parsed) - List.len(people)) score <- function(team: Str) -> F64 Result.with_default(Dict.get(totals, team), 0) score("red") + 2 * score("blue") + 3 * score("green") + errors}i <- seq_len(60000L)rows <- List.from_r(paste0("user", i, ",", ifelse(i %% 17L == 0L, "x", as.character(i %% 90L)), ",", (i %% 50L) / 2, ",", c("red", "blue", "green")[i %% 3L + 1L]))measure("team_scores", function() team_scores(rows))testthat suite testthat 5.33x
Many small test_that() blocks with expect_equal, expect_error and expect_warning: testthat's condition machinery. Source
Time series and dates timeseries 2.09x
xts and zoo series merged, lagged and rolled, lubridate parsing and month arithmetic, base Date sequences. Source
Argument validation validation 5.33x
Small functions with defaults, `...` forwarding, match.arg, stopifnot, missing() and match.call(). Source
Every program reports its time through harness.R, which also prints the checksum that all engines must agree on.
How it was measured
Section titled “How it was measured”The published numbers measure the build you download: the official Linux x86_64 archive of a
tagged release, which is profile-guided and laid out by BOLT (tools/layout/optimize.sh). The
runner unpacks the archive into a private directory where its ry extracts the runtime and base R
it embeds, and the line under each chart names the release and the first digits of the archive’s
sha256. A suite whose line names a commit instead was measured on a plain release build of that
commit (cargo build --release), without the release layout.
A run measures several rounds. Each round runs every program on every engine once, with the programs in an order shuffled per round and the engines in an order shuffled per program, from a recorded seed. Each ratio is formed inside one round, GNU R’s time over the engine’s, and the reported speed-up is the median of those per-round ratios. Pairing matters because the measuring machines are shared cloud VMs whose effective CPU speed drifts with other tenants’ load: a slow drift moves both engines of one round together, so it cancels in the ratio. Each speed-up and each geometric mean carries a 95% bootstrap interval over the rounds.
What one timed run covers differs by suite:
| Suite | One process runs | The time includes |
|---|---|---|
| Public R JIT benchmarks | the program once | byte compilation and JIT tier-up, not start-up |
| Package test suites | the package’s tests | start-up and loading the package and its imports |
| Numeric kernels, application workloads | the program once cold, then five times warm | the median warm run only |
The runner, not this page, judges the data:
- Checksums. Every engine must print the same checksum as GNU R for a program, or the run fails and nothing is written. A numeric checksum may differ by a relative 1e-10, because a typed program may sum in a different order. A program that fails on any engine also fails the run.
- Package tests. The packages suite is the exception, because there the program is the
package’s own test suite. Test counts that differ between the engines are flagged as tests
differ, and the package stays in the geometric mean. A test script that ends in an R error, as
R CMD checkreads a failing script, counts as one failed test. A test suite that crashes or does not run to the end on an engine is recorded as failing there, which leaves the package out of the geometric mean. - Too short. A program GNU R finishes in under 0.1 s does too little work for a stable ratio, so it is flagged too short and left out of every geometric mean. A ry time under 0.1 s is flagged too, but it counts, because that speed is what the suite measures.
- Wide intervals. A ratio whose interval reaches more than 10% from its median gets extra rounds, and it is flagged wide interval if they do not narrow it.
- Refused typed programs. Where the typed core refuses part of a typed program, that part runs in the interpreter, and its flag gives the refusal.
| Suite | Reproduce | Baseline | Engines | Samples |
|---|---|---|---|---|
| Public R JIT benchmarks | just bench public --release ARCHIVE --write | GNU R 4.6.2, BLAS libRblas.so | GNU R, ry, ry typed, ry typed, AOT | 10 paired rounds, 10 more for each wide interval, seed 1 |
| Package test suites | just bench packages --release ARCHIVE --write | GNU R 4.6.2, BLAS libRblas.so | GNU R, ry | 10 paired rounds, 10 more for each wide interval, seed 1 |
| Benchmark code bases | just bench codebases --release ARCHIVE --write | GNU R 4.6.2, BLAS libRblas.so | GNU R, ry, ry, JIT off | 10 paired rounds, seed 1 |
| Numeric kernels (ours) | just bench kernels --release ARCHIVE --write | GNU R 4.6.2, BLAS libRblas.so | GNU R, ry, ry typed, ry typed, AOT, ry typed, installed | 10 paired rounds, 10 more for each wide interval, seed 1 |
| Application workloads (ours) | just bench applications --release ARCHIVE --write | GNU R 4.6.2, BLAS libRblas.so | GNU R, ry, ry typed, ry typed, AOT, ry typed, installed | 10 paired rounds, 10 more for each wide interval, seed 1 |
To reproduce a suite, run its command from the table on a machine with GNU R; the packages suite
first needs just bench-packages install. Without --release, a run measures the local release
build in target/release, which is how to compare two builds of your own (--baseline), and
--ry PATH measures the release build at another path. With
--write, the runner stores tools/bench/<suite>/results.json with the release tag, the archive’s
file name and sha256, and the commit the tag names, and just readme rewrites the README summary
from it. --write refuses a nightly archive, a local build, and a working tree with a change to a
tracked file or an untracked file under crates/ or tools/bench/, so the stored programs
reproduce the measurement. The README summary warns when the suites were measured on different machines (CPU
model or kernel release, ignoring a Firecracker guest’s -fc-vNNN build tag) or against a GNU R on a different BLAS, because their ratios are then not
comparable.