Ractors vs threads vs fork: 28 Ruby benchmarks on 1–8 cores
The 28 programs from Spinel’s benchmark set, each run as 8 identical tasks under threads, Ractors and fork on 1, 2, 4 and 8 pinned cores, Ruby 4.0.9 with YJIT. fork ran 6.5–8.0× faster than one thread on every program. Ractors reached 5.3–7.9× on the 14 programs that allocate fewer than 0.11 million objects per second on one thread, and 0.26–2.0× on the 13 that allocate 2.4 million or more; 4 of those ran slower than on one thread. Why allocation stops Ractors, and what each model costs per message and per start, is in Ruby Ractors: isolation, message cost and where they scale.
All 28 programs
| Program | 1 thread, runs/s | 8 threads | 2 Ractors | 4 Ractors | 8 Ractors | 8 Ractors, min–max | 8 × fork | ΣPSS 8 Ractors / 8 forks | Allocated objects/s, 1 thread |
|---|---|---|---|---|---|---|---|---|---|
| scales | |||||||||
partial_sums | 0.91 | 1.00× | 2.01× | 4.00× | 7.91× | 7.80–8.01 | 7.99× | 22 / 63 MB | 1 k |
matmul | 3.18 | 1.00× | 2.01× | 3.98× | 7.69× | 7.62–7.73 | 7.95× | 48 / 74 MB | 71 k |
life | 2.07 | 1.00× | 1.95× | 3.88× | 7.56× | 7.53–7.71 | 8.00× | 63 / 328 MB | 435 |
sieve | 2.16 | 0.98× | 2.00× | 3.87× | 7.44× | 7.21–7.55 | 7.63× | 86 / 242 MB | 1 k |
so_mandelbrot | 0.79 | 1.01× | 1.99× | 3.94× | 7.41× | 7.24–7.48 | 8.00× | 24 / 38 MB | 101 k |
so_lists | 4.15 | 0.97× | 1.97× | 3.83× | 7.07× | 6.93–7.14 | 7.90× | 166 / 476 MB | 7 k |
nqueens | 13.86 | 0.59× | 1.94× | 3.98× | 7.04× | 6.97–7.13 | 8.04× | 24 / 32 MB | 665 |
sudoku | 29.10 | 0.99× | 1.98× | 3.83× | 7.01× | 6.82–7.09 | 7.95× | 59 / 269 MB | 12 k |
| partly | |||||||||
fib | 7.28 | 1.00× | 1.68× | 3.33× | 6.40× | 6.30–6.53 | 7.99× | 22 / 26 MB | 44 |
tak | 7.44 | 1.00× | 1.66× | 3.31× | 6.33× | 6.08–6.43 | 7.98× | 22 / 27 MB | 60 |
ackermann | 11.34 | 1.00× | 1.69× | 3.36× | 6.30× | 6.12–6.50 | 7.99× | 26 / 32 MB | 91 |
tarai | 9.75 | 1.00× | 1.66× | 3.31× | 6.29× | 6.14–6.40 | 7.98× | 22 / 27 MB | 78 |
str_concat | 5,115 | 0.94× | 1.86× | 3.51× | 5.77× | 5.64–5.88 | 6.47× | 78 / 194 MB | 46 k |
fannkuch | 532 | 0.85× | 1.85× | 3.83× | 5.29× | 5.12–5.48 | 7.82× | 24 / 69 MB | 6 k |
rbtree | 6.73 | 0.99× | 1.75× | 2.99× | 4.28× | 4.07–4.51 | 7.95× | 43 / 63 MB | 1.5 M |
| stalls | |||||||||
linked_list | 5.16 | 0.87× | 1.36× | 1.84× | 2.00× | 1.66–2.27 | 7.88× | 145 / 227 MB | 11.3 M |
ao_render_rs | 0.72 | 0.97× | 1.74× | 2.46× | 1.99× | 1.76–2.11 | 7.96× | 24 / 54 MB | 5.4 M |
gcbench | 0.59 | 0.98× | 1.40× | 1.76× | 1.92× | 1.78–2.10 | 7.77× | 748 / 702 MB | 18.2 M |
bigint_fib | 10,380 | 0.99× | 1.63× | 2.08× | 1.62× | 1.45–1.73 | 7.75× | 29 / 82 MB | 9.5 M |
fasta_rs | 494 | 0.96× | 1.49× | 1.82× | 1.62× | 1.55–1.73 | 7.83× | 32 / 70 MB | 6.1 M |
csv_process | 1.20 | 1.00× | 1.38× | 1.75× | 1.35× | 1.22–1.40 | 7.70× | 36 / 57 MB | 7.3 M |
pidigits | 7,869 | 0.99× | 1.54× | 1.73× | 1.33× | 1.29–1.36 | 7.86× | 29 / 70 MB | 14.5 M |
io_wordcount_rs | 13.06 | 0.94× | 1.51× | 1.95× | 1.28× | 1.23–1.34 | 7.95× | 24 / 51 MB | 8.6 M |
huffman | 34.46 | 0.62× | 1.00× | 1.37× | 1.17× | 1.14–1.19 | 7.80× | 82 / 121 MB | 6.9 M |
| slower | |||||||||
template | 1.44 | 0.98× | 1.33× | 1.38× | 0.80× | 0.76–0.84 | 7.98× | 23 / 42 MB | 15.2 M |
binary_trees | 94.64 | 0.96× | 1.22× | 1.07× | 0.77× | 0.68–0.89 | 7.79× | 27 / 56 MB | 12.9 M |
json_parse | 3.78 | 0.95× | 1.26× | 1.20× | 0.77× | 0.72–0.79 | 7.88× | 23 / 46 MB | 15.5 M |
splay | 16.18 | 0.97× | 0.96× | 0.75× | 0.26× | 0.21–0.31 | 6.62× | 62 / 99 MB | 2.4 M |
The allocation column is objects allocated by one run, counted once per program after two warm-up runs (alloc28.rb), times the 1-thread runs per second. The 1-thread column is runs of the program per second; every other column is a speed-up over the 1-thread cell of the same trial. Median of 9 trials (18 for fib, gcbench and json_parse, which ran on both machines). Programs are grouped by their 8-Ractor speed-up: scales ≥ 7×, partly 4–7×, stalls 1–4×, slower < 1×.
- 8 threads: 0.59–1.01×.
nqueens(0.59×) andhuffman(0.62×) run slower on 8 threads than on one. - 8 Ractors: 8 programs at 7.0–7.9×, 7 at 4.3–6.4×, 9 at 1.2–2.0×, 4 below 1×. 11 programs are faster at 2 or 4 Ractors than at 8, e.g.
json_parse1.26× at 2 and 0.77× at 8. - Allocation rate (objects allocated per run, counted with
GC.stat(:total_allocated_objects), × 1-thread runs per second): < 0.11 M/s → 5.3–7.9× on 8 Ractors (14 programs);rbtreeat 1.5 M/s → 4.3×; ≥ 2.4 M/s → 0.26–2.0× (13 programs). It does not explain everything:fib,tak,taraiandackermannallocate under 100 objects per second and stop at 6.3×, already 1.66–1.69× on 2 Ractors. - 8 forks: 6.5–8.0× on all 28;
str_concat(6.47×) andsplay(6.62×) are the lowest.
Memory
ΣPSS is the proportional set size of the Ractor process, or of the parent plus 8 children under fork, at the end of the cell; pages shared between processes count once in total.
- 8 Ractors used less memory than 8 forks on 27 of 28 programs:
life63 against 328 MB,so_lists166 against 476 MB,sudoku59 against 269 MB. - The exception is
gcbench: 748 MB with 8 Ractors, 702 MB with 8 forks.
Three patched programs
The harness loads every constant through Ractor.make_shareable in all three models, so every model runs the same code. Three programs needed a patch; the originals’ results are in the data.
| Program | Original | Patch |
|---|---|---|
ao_render | RAND = Rand.new becomes frozen; Rand#rand changes it → FrozenError in every model | one Rand per run in Thread.current |
fasta | the global $last → Ractor::IsolationError in Ractors only (threads and fork ran: 8 forks 7.80×) | Thread.current[:fasta_last] |
io_wordcount | every worker writes, reads and deletes one fixed /tmp file | one file per worker |
Each patch does the same work per run as the original and uses the original’s runs per task. fasta_rs costs 3.5 % on one thread (494 against 512 runs per second).
--- bm_fasta.rb
+++ bm_fasta_rs.rb
-$last = 42
+Thread.current[:fasta_last] = 42
def gen_random(max)
- $last = ($last * IA + IC) % IM
- max * $last / IM
+ Thread.current[:fasta_last] = (Thread.current[:fasta_last] * IA + IC) % IM
+ max * Thread.current[:fasta_last] / IM
end
--- bm_ao_render.rb
+++ bm_ao_render_rs.rb
-RAND = Rand.new
+# RAND: one Rand per run, thread-local (was a mutable constant)
- r = RAND.rand
- phi = 2.0 * 3.14159265 * RAND.rand
+ r = Thread.current[:ao_rand].rand
+ phi = 2.0 * 3.14159265 * Thread.current[:ao_rand].rand
# File.open("ao.ppm", "w") do |fp|
+Thread.current[:ao_rand] = Rand.new # one Rand per run (was the mutable constant RAND)
--- bm_io_wordcount.rb
+++ bm_io_wordcount_rs.rb
-File.open("/tmp/spinel_io_wf.txt", "w") do |f|
+wf_path = "/tmp/spinel_io_wf_#{Process.pid}_#{Thread.current.object_id}.txt" # one file per worker (was one fixed path)
+File.open(wf_path, "w") do |f|
(the same change on the two reads and the delete)
GC settings
The knowledge article’s String, Hash and JSON.parse workloads (rb3.rb) under four settings of the garbage collector; 1 thread, 8 Ractors and 8 forks, 9 trials on one machine. “1M slots” sets RUBY_GC_HEAP_0_INIT_SLOTS to RUBY_GC_HEAP_4_INIT_SLOTS to 1,000,000; “growth 4” adds RUBY_GC_HEAP_GROWTH_FACTOR=4 and RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO=0.5; “GC off” calls GC.disable before the timed reps.
| Workload | Setting | 1 thread, tasks/s | 8 Ractors | 8 forks | GCs per rep, 8 Ractors | GC share, 8 Ractors | 8 Ractors, trial range | Peak memory, 8 Ractors |
|---|---|---|---|---|---|---|---|---|
| String alloc | default | 1,544 | 0.92× | 7.89× | 92.7 | 31 % | 15 % | 19 MB |
| String alloc | 1M slots | 1,640 | 2.96× | 8.85× | 3.2 | 38 % | 3 % | 59 MB |
| String alloc | 1M slots + growth 4 | 1,640 | 2.91× | 8.83× | 3.2 | 38 % | 6 % | 59 MB |
| String alloc | GC off | 1,526 | 3.05× | 7.99× | 0.0 | 0 % | 17 % | 2.6 GB |
| Hash alloc | default | 4,999 | 1.04× | 7.64× | 32.4 | 33 % | 22 % | 19 MB |
| Hash alloc | 1M slots | 4,827 | 2.81× | 9.04× | 0.7 | 45 % | 9 % | 129 MB |
| Hash alloc | 1M slots + growth 4 | 4,552 | 3.05× | 9.97× | 0.5 | 47 % | 52 % | 165 MB |
| Hash alloc | GC off | 4,239 | 1.94× | 9.07× | 0.0 | 0 % | 12 % | 3.3 GB |
JSON.parse | default | 6,506 | 1.14× | 7.69× | 16.6 | 33 % | 15 % | 19 MB |
JSON.parse | 1M slots | 6,342 | 2.58× | 8.74× | 0.6 | 49 % | 5 % | 115 MB |
JSON.parse | 1M slots + growth 4 | 6,315 | 5.63× | 8.54× | 0.5 | 49 % | 21 % | 151 MB |
JSON.parse | GC off | 6,023 | 1.92× | 8.32× | 0.0 | 0 % | 11 % | 3.1 GB |
Speed-ups are over 1 thread under the same setting. GC share is GC.stat[:time] over wall time.
- 1M slots: 8 Ractors 2.6–3.0× one thread, against 0.9–1.1× by default. Collections per rep fall from 17–93 to 0.6–3.2; peak memory rises from 19 MB to 59–129 MB.
- Growth 4 on top: Strings and Hashes stay at 2.9–3.1× (the Hash cell ranged 52 % across trials);
JSON.parsereaches 5.6× (range 21 %). - GC off: 3.1× on Strings, 1.9× on Hashes and
JSON.parse, at 2.6–3.3 GB peak memory. A Ractor whose slot cache runs dry still takes the cross-Ractor lock to refill it. - With 1M slots, 8 Ractors spend 38–49 % of the wall time in GC (fewer, longer collections) and still run 2.6–3.0× faster.
fork: 7.6–7.9× by default, 8.5–10.0× with the bigger heaps. 8 forks run under both clusters’ L3 caches (24 MB, against 8 MB for one thread), which made memory-heavy children 5–18 % faster in the cache check; these cells were not checked separately.
Task size
How small may a task be before one message per task eats the gain? Each task is fib(n), sent as its own message to one of 8 Ractors, or as one line over a pipe to one of 8 forked children (64 in flight per child). The baseline runs the same tasks in a loop on one core. Tasks per rep are fixed per n: about 0.4 s of work on one core from fib(10) up, capped at 400,000 tasks below that.
| Task | One task on one core | 8 Ractors | 8 forks | 8 Ractors, trial range |
|---|---|---|---|---|
fib(1) | 0.016 µs | 0.03× | 0.01× | 84 % |
fib(5) | 0.117 µs | 0.17× | 0.06× | 23 % |
fib(10) | 1.3 µs | 2.29× | 0.65× | 28 % |
fib(15) | 14.7 µs | 5.46× | 4.48× | 4 % |
fib(18) | 62.2 µs | 6.31× | 6.74× | 2 % |
fib(20) | 163 µs | 6.21× | 7.13× | 2 % |
fib(22) | 426 µs | 6.39× | 7.45× | 2 % |
fib(25) | 1.81 ms | 6.49× | 7.67× | 1 % |
- Ractors beat one core from tasks of 1.3 µs (
fib(10): 2.3×) and reach 5.5–6.5× from 15 µs. With smaller tasks they move 1.4–1.7 million messages per second, and the trials range 23–84 %. forkover pipes runs 0.65× at 1.3 µs, 4.5× at 15 µs, 6.7× at 62 µs and 7.7× at 1.8 ms; it moves about 0.5 million tasks per second at most.- Ractors are ahead up to 15 µs per task (5.46× against 4.48×),
forkfrom 62 µs (6.74× against 6.31×).
Shared read-only data
8 workers each scan one Array of 500,000 Strings of 100 B twice per rep. Ractors receive it after one Ractor.make_shareable (0.109 s); forked children inherit it. Every model runs GC.start and GC.compact before starting its workers, as a pre-forking server does before forking.
| Model | Scans/s | Speed-up | Trial range | ΣPSS | ΣRSS |
|---|---|---|---|---|---|
| 1 thread | 47.7 | 1.00× | 2 % | 121 MB | 122 MB |
| 1 Ractor | 47.6 | 1.00× | 2 % | 120 MB | 121 MB |
| 1 fork | 47.6 | 1.00× | 3 % | 121 MB | 236 MB |
| 8 threads | 32.2 | 0.68× | 2 % | 121 MB | 122 MB |
| 8 Ractors | 360.2 | 7.56× | 27 % | 122 MB | 123 MB |
| 8 forks | 477.8 | 10.02× | 1 % | 138 MB | 1,068 MB |
- 8 Ractors: 7.6× (trials range 27 %); 8 forks: 10.0×; 8 threads: 0.68×.
- One worker alone scans the same in every model: 47.6–47.7 scans/s for 1 thread, 1 Ractor and 1 forked child (median of 9 each; the 1 Ractor and 1 fork rows come from a separate 9-trial run right after the main one). 8 forks scan 59.7 per child.
- The extra speed comes from the CPU’s shared caches. Cores 0–9 share an 8 MB L3 and cores 10–19 a 16 MB L3; 1 worker runs on core 1, 8 workers on cores 1–4 and 10–13. A separate gated run (9 trials per cell,
fork) measured scans per second per child:
| Cores | 1 child | 4 children |
|---|---|---|
| core 1 / cores 1–4 (8 MB L3) | 47.6 | 53.5 |
| core 10 / cores 10–13 (16 MB L3) | 49.9 | 59.0 |
| cores 1–4 and 10–13, 8 children | 59.5 per child |
The bigger L3 adds 5 % for one child. Children that read the same pages through one shared L3 each run 12–18 % faster than one alone, consistent with each page coming from memory once for several cores. Every 8-against-1 ratio of memory-heavy work in this article (this section and the GC settings) includes both effects; CPU-bound programs stay at or below 8.04×.
- ΣPSS is 122 MB for 8 Ractors and 138 MB for 8 forks, against 120 MB for one worker: both hold one copy. Summed RSS for
fork(1,068 MB) counts the shared pages once per process.
Two machines
The 28 programs were split across two identical machines; fib, gcbench and json_parse ran on both:
| Program | Cell | Machine A, runs/s | Machine B, runs/s | Gap |
|---|---|---|---|---|
fib | 1 thread | 7.280 | 7.285 | +0.1 % |
fib | 8 Ractors | 46.586 | 46.558 | −0.1 % |
fib | 8 forks | 58.142 | 58.168 | +0.0 % |
gcbench | 1 thread | 0.593 | 0.594 | +0.2 % |
gcbench | 8 Ractors | 1.144 | 1.141 | −0.3 % |
gcbench | 8 forks | 4.628 | 4.615 | −0.3 % |
json_parse | 1 thread | 3.783 | 3.765 | −0.5 % |
json_parse | 8 Ractors | 2.849 | 2.951 | +3.6 % |
json_parse | 8 forks | 29.776 | 29.802 | +0.1 % |
All 30 anchor cells (every model and W) agree within 1.1 %, except json_parse at 4 and 8 Ractors (+2.8 %, +3.6 %).
Gates and discards
| Run | Rows kept | Re-run: machine busy | Re-run: foreign load on the cores | Re-run: GPU busy | YJIT gate (6 probes, spread) |
|---|---|---|---|---|---|
| 28 programs, both machines | 2,970 | 105 | 0 | 0 | 0.16–0.83 % |
| knowledge article cells, 3 passes | 1,161 | 17 | 0 | 0 | none; fib on 1 Ractor ran 2,176–2,178 tasks/s in all 9 trials |
| GC settings, task size, shared data, cache check | 765 | 0 | 0 | 0 | 0.24–0.92 % |
The 2,970 rows include 126 expected failures: the unpatched ao_render in every model and the unpatched fasta in Ractors. In every kept cell the rest of the machine used at most 4.99 cores and the GPU 0 %.
Downloads
- Raw rows, one JSON line per cell with its load readings: machine A, 16 programs, machine B, 17 programs, GC settings, task size and shared data, knowledge-article passes 1, 2, 3. 1-worker shared-data baselines: c3w1.jsonl; cache check: l3.jsonl. The
.logfiles next to them list every discard. - Superseded: the first task-size and shared-data run, c23.jsonl from c23_v1.rb. Its fork side refilled the children one at a time, and only its fork cell compacted the heap; both are fixed in
c23.rb, and the tables above come from the re-run. - Harness: bm28.rb, run28g.sh, runxg.sh, rb3.rb, c23.rb, lock.sh, calib.jsonl, alloc28.rb and its allocation counts, program lists A and B, the three patched programs (ao_render_rs, io_wordcount_rs).
Related
- Ruby Ractors: isolation, message cost and where they scale — the API, the six workloads, message cost, why the GC stops Ractors.
- Spinel vs JRuby vs CRuby (YJIT): 28 Ruby benchmarks — the same 28 programs on three Ruby implementations, one core.
- Ruby vs Rust benchmarks: eight everyday fragments — threads, Ractors and fork on
cpu,jsonandioon x86. - Ruby vs Python concurrency — GVL vs GIL, Ractors next to subinterpreters.
Benchmark setup
| Setup | Details |
|---|---|
| Programs | the 28 programs in Spinel’s benchmark/ directory, the same set as in Spinel vs JRuby vs CRuby (YJIT): 28 Ruby benchmarks; 25 run unchanged, 3 need a 2–4 line patch to run as parallel copies (below) |
| Ruby | 4.0.9, image ruby@sha256:3251898a…2cd31d (full digest in the commands below), arm64, --yjit |
| Models | threads: W threads in one process (one GVL) · Ractors: W Ractors in one process (one GVL each) · fork: W pre-forked child processes fed over pipes, the shape of a Puma cluster |
| Workers | W = 1, 2, 4, 8 Ractors or forked children, and 1 and 8 threads, each on exactly W cores |
| Hosts | two identical 20-core ARM64 servers (10 × Cortex-X925 + 10 × Cortex-A725). Benchmarks on the A725 cores at 2.8 GHz, governor performance: --cpuset-cpus=1, 1-2, 1-4, 1-4,10-13. Each program ran on one host; three anchor programs ran on both |
| Isolation | every systemd service, every other container and every movable IRQ confined to the ten X925 cores for the whole run (cgroup v2 cpuset.cpus on system.slice, user.slice, init.scope); benchmark containers in their own slice |
| Load gates | a cell is discarded and run again when, during that cell, (1) other processes used more than 0.05 + 0.03 × W cores of the benchmark’s own cores, (2) the rest of the machine used more than 5 cores — a busy neighbour slows allocation-heavy cells by 10–14 % through the shared memory system even when no core is shared — or (3) the GPU, which shares that memory, was more than 5 % busy (a GPU serving a model slowed memory-bound cells 2.5×). After (2) or (3) the cell waits 30 s. Discarded cells are never counted |
| YJIT gate | before every pass, 6 processes of 64 × fib(22) on one benchmark core must agree within 10 % (on the X925 cores YJIT speed varies up to 14× between processes); all 12 gates gave 0.0274–0.0277 s |
| Correctness | every run of every program, in every model, compares its output with Spinel’s .expected file; one mismatch fails the cell |
| Trials | 3 passes × 3 interleaved trials = 9 measurements per cell; the median is reported |
Method
bm28.rb turns one Spinel program into a task. Prism splits the file: method, class and module definitions and constant assignments load once in the main Ractor (constants through Ractor.make_shareable, in every model); every other top-level statement becomes __bm_run, which captures $stdout into a per-thread buffer. A task runs __bm_run k times and compares every output with the program’s .expected. k comes from calib.jsonl, one value per program for both machines, chosen so one task takes at least 50 ms on one core.
Each rep sends 8 tasks to W workers round-robin: W threads fed by a Queue, W Ractors fed by send and answering on one Ractor::Port (with #monitor, so a worker that dies fails the cell instead of hanging it), or W forked children fed over pipes. 1 warm-up rep, then at least 2 reps and 3 s; the cell reports the median rep as runs per second (8 × k ÷ rep time) and ΣPSS/ΣRSS from /proc/<pid>/smaps_rollup. A program that cannot run in a Ractor prints its error as the result.
The order inside a pass: trial 1 of every cell of every program, then trial 2, then trial 3. A speed-up is the ratio to the 1-thread cell of the same program in the same trial; the tables give the median of the 9 ratios and the figure marks programs whose ratios ranged wider than ±5 %. Machine A ran 16 programs, the first (superseded) task-size and shared-data run and the 3 passes of the knowledge article’s cells; machine B ran 17 programs, the GC settings and the corrected task-size and shared-data runs. Machine A ran for 5.9 hours, machine B for 4.8.
The scripts are a record of this run on this hardware: core sets, the core lock and the work directory are written into them, not read from a configuration.
One cell, as run28g.sh starts it:
docker run --rm --cgroup-parent=bench651.slice --cpuset-cpus=1-4,10-13 -v "$PWD":/b -w /b \
ruby@sha256:3251898a6b7ff1275a0dc279d401889c6c743c1fb3292fa3ce1a2e12fc2cd31d \
timeout 900 ruby --yjit bm28.rb benchmark/bm_life.rb ractors 8 1
bm28.rb:
# bm28.rb <bm_file> <model> <W> <k> — one Spinel program under threads / ractors / fork, W workers on W cores.
# Prism splits the program: def/class/module/constant writes load once in the main Ractor (constants through
# Ractor.make_shareable, the same in every model); every other top-level statement becomes __bm_run, which
# captures $stdout. A task runs __bm_run k times and checks every output against Spinel's .expected.
# TASKS tasks per rep, split round-robin over W workers; 1 warm-up rep, then >= 2 reps and >= 3 s; median rep.
# One JSON line on stdout; a non-Ractor-safe program prints {error: …} and exits 0 (it is a result, not a crash).
require "prism"
require "stringio"
require "json"
require "etc"
Warning[:experimental] = false
file, model, w, k = ARGV.shift, ARGV.shift, Integer(ARGV.shift), Integer(ARGV.shift)
ARGV.clear
TASKS = 8
def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
def median(a) = a.sort[a.size / 2]
def pss_kb(pid) = File.read("/proc/#{pid}/smaps_rollup")[/^Pss:\s+(\d+)/, 1].to_i
def rss_kb(pid) = File.read("/proc/#{pid}/smaps_rollup")[/^Rss:\s+(\d+)/, 1].to_i
bm = File.basename(file, ".rb").sub(/\Abm_/, "")
out = { test: "bm28", bm: bm, model: model, w: w, k: k, tasks: TASKS, ruby: RUBY_VERSION,
yjit: defined?(RubyVM::YJIT) && RubyVM::YJIT.enabled?, cpus: Etc.nprocessors }
EXPECTED = Ractor.make_shareable(File.read("#{file}.expected"))
stmts = Prism.parse(File.read(file)).value.statements.body
DEFN = [Prism::DefNode, Prism::ClassNode, Prism::ModuleNode, Prism::ConstantWriteNode, Prism::ConstantPathWriteNode]
defs, body = stmts.partition { |n| DEFN.any? { n.is_a?(_1) } }
defs_src = defs.map { |n| n.is_a?(Prism::ConstantWriteNode) ? "#{n.name} = Ractor.make_shareable(#{n.value.slice})" : n.slice }.join("\n")
TOPLEVEL_BINDING.eval(defs_src, file)
TOPLEVEL_BINDING.eval(<<~RUBY, file)
def __bm_run
o = StringIO.new; Thread.current[:bm_out] = o
begin
#{body.map(&:slice).join("\n")}
ensure
Thread.current[:bm_out] = nil
end
o.string
end
def __bm_task(k)
k.times { raise "output != .expected" unless __bm_run == EXPECTED }
1
end
RUBY
Ractor.make_shareable(ARGV)
class BmOut # $stdout forwarder: output goes to the calling thread's buffer, in every model
def target = Thread.current[:bm_out] || STDOUT # inside __bm_run: the run's buffer; outside (fork's flush, at_exit): the real stdout
def write(*a) = target.write(*a)
def method_missing(m, *a, &b) = target.__send__(m, *a, &b)
def respond_to_missing?(*) = true
end
$stdout = BmOut.new
begin
__bm_task(1) # the program must be correct in the main Ractor first
rescue Exception => e
STDOUT.puts JSON.generate(out.merge(error: "main: #{e.class}: #{e.message.lines.first.to_s.strip[0, 160]}")); exit 0
end
shares = Array.new(w) { |i| (i...TASKS).step(w).count }
rep = case model
when "threads"
Thread.abort_on_exception = true # a worker that raises ends the process (the cell fails) instead of leaving back.pop waiting
qs = Array.new(w) { Queue.new }; back = Queue.new
w.times { |i| Thread.new { while qs[i].pop; back << shares[i].times.sum { __bm_task(k) }; end } }
-> { qs.each { _1 << true }; Array.new(w) { back.pop }.sum }
when "ractors"
back = Ractor::Port.new
begin # one task in a Ractor first: a program that is not Ractor-safe is a result, not a hang
Ractor.new(k) { |k| $stdout = BmOut.new; __bm_task(k) }.value
rescue Ractor::RemoteError => e
STDOUT.puts JSON.generate(out.merge(error: "ractor: #{e.cause.class}: #{e.cause.message.lines.first.to_s.strip[0, 160]}")); exit 0
end
rs = Array.new(w) { |i| Ractor.new(shares[i], k, back) { |n, k, b| $stdout = BmOut.new; while Ractor.receive; b << n.times.sum { __bm_task(k) }; end } }
rs.each { _1.monitor(back) } # a worker that dies posts :aborted to the results port -> the task count check fails the cell
-> { rs.each { _1.send(true) }; Array.new(w) { v = back.receive; raise "ractor worker died: #{v.inspect}" unless v.is_a?(Integer); v }.sum }
when "fork"
kids = Array.new(w) do |i|
cr, cw = IO.pipe; pr, pw = IO.pipe
pid = fork { cw.close; pr.close; while cr.gets; pw.puts(shares[i].times.sum { __bm_task(k) }); end; exit! 0 }
cr.close; pw.close; [cw, pr, pid]
end
-> { kids.each { |cw, _, _| cw.puts "go" }; kids.sum { |_, pr, _| pr.gets.to_i } }
else abort "model?"
end
begin
abort "task count" unless rep.call == TASKS # warm-up rep
times = []; t_end = now + 3.0
while times.size < 2 || now < t_end
t = now; abort "task count" unless rep.call == TASKS; times << now - t
end
rescue Ractor::RemoteError => e
STDOUT.puts JSON.generate(out.merge(error: "ractor: #{e.cause.class}: #{e.cause.message.lines.first.to_s.strip[0, 160]}")); exit 0
end
pids = [Process.pid] + (model == "fork" ? kids.map { _1[2] } : [])
t = median(times)
STDOUT.puts JSON.generate(out.merge(reps: times.size, median_s: t.round(6), runs_per_s: (TASKS * k / t).round(3),
pss_kb: pids.sum { pss_kb(_1) }, rss_kb: pids.sum { rss_kb(_1) }, procs: pids.size, checksum: EXPECTED.bytesize))
if model == "fork" # close every command pipe first: each later child holds copies of the earlier children's pipes,
kids.each { |cw, _, _| cw.close } # so closing and waiting one by one deadlocks; all closed, they exit last-to-first
kids.each { |_, _, pid| Process.wait(pid) }
end