5 programs measured with axle bench: crew_fanout, fan_out_scaling, spawn_await_throughput, spawn_burst, wake_hops. Run time, peak RAM at compile and run, and binary size, with the exact source for each language.
Benchmarks for v0.23.0
A standing crew of eleven workers and the caller, woken and collected through two semaphores — the per-frame fan-out of a worker pool. Run by hand: it prints a matrix per variant (Thread::run crew, spawned crew) and its `check` mode is the manual guard for the crew wait paths, timed on a quiet machine rather than a shared runner.
| Variant | Run | Compile | Output | ||
|---|---|---|---|---|---|
| Run time | RAM | Compile time | RAM | Binary | |
| Axle -O2 | 152 ms | 44.7 MB | 212 ms | 127.4 MB | 507 KB |
| Axle -O3 | 153 ms | 44.7 MB | 233 ms | 126.2 MB | 508 KB |
| Axle -O1 | 165 ms | 44.7 MB | 144 ms | 126.4 MB | 505 KB |
| Axle -O0 | 327 ms | 44.7 MB | 97 ms | 126.3 MB | 510 KB |
// EXPECTED_EXIT: 0
// Crew fan-out — a standing crew of 11 workers and the caller, woken and
// collected through two semaphores, the shape of every per-frame fan-out
// (smalt's `WorkerPool` is this program with a job table in front).
//
// crew_fanout every variant
// crew_fanout <thread|task> <spins> one variant
// crew_fanout check thread and task at spins 0, exit 1 on a miss
//
// Any of the words above may be followed by `fine`, which asks the process for
// a 1 ms timer resolution first (the timeBeginPeriod(1) a program with a window
// sets); it does nothing off Windows.
//
// thread : the crew is started with Thread::run — a plain frame per worker.
// task : the crew is spawned — a parked task per worker.
// spins : tryAcquire attempts a waiter makes before it falls back to acquire.
//
// Per variant it prints the mean and worst empty fan-out (the two handoffs
// and nothing else), the mean loaded pass (each share a fixed number of steps),
// how many shares ran at once, how late the caller saw the last share end, and
// how many OS threads the 11 workers live on (read once, as each starts).
//
// `check` is the manual guard for the crew wait paths: it fails when the mean
// empty fan-out reaches EMPTY_LIMIT_US, the mean loaded pass reaches
// LOADED_LIMIT_US, the caller sees the end LATE_LIMIT_US late or more, or the
// task crew starts on fewer OS threads than the pool can give it (one carrier is
// the caller's, so at most one fewer than the processors). Timings on a shared
// runner are not a fact, so this is run by hand on a quiet machine and is not
// part of CI. Set AXLE_CARRIERS to the pool you mean to check against only if it
// is not the processor count.
//
// Without `fine` it runs at the process's default timer resolution, which is
// what a program without a window gets. On Windows that makes a 1 ms sleep last
// ~15.6 ms.
//
// The reference to compare against is the same crew on a kernel semaphore under
// kernel threads, 11 workers on 11 threads: a wake that costs one kernel
// handoff, whatever the timer resolution.
use std::concurrent::{ AtomicBoolean, AtomicI32, Semaphore, Thread };
use std::lang::{ IllegalStateException, InterruptedException, IndexOutOfBoundsException, ParseException };
use std::sys::process::{ argAt };
use std::sys::sysinfo::cpuCount;
use std::time::monotonicNanos;
@target(os = windows)
extern "C" from "winmm" {
fn timeBeginPeriod(ms : i32) : i32;
}
@target(os = windows)
fn fineTimer() : void {
let r : i32 = timeBeginPeriod(1);
}
@target(os = linux)
fn fineTimer() : void {
}
@target(os = macos)
fn fineTimer() : void {
}
@target(os = windows)
extern "C" fn GetCurrentThreadId() : i32;
@target(os = linux)
extern "C" fn gettid() : i32;
@target(os = windows)
fn osThread() : i32 {
return GetCurrentThreadId();
}
@target(os = linux)
fn osThread() : i32 {
return gettid();
}
const SHARES : i32 = 12;
const EMPTY_PASSES : i32 = 200;
const BUSY_PASSES : i32 = 60;
const SHARE_STEPS : i32 = 200000;
const EMPTY_LIMIT_US : i64 = 50;
const LOADED_LIMIT_US : i64 = 400;
const LATE_LIMIT_US : i64 = 50;
class Report {
pub emptyUs : i64,
pub worstUs : i64,
pub busyUs : i64,
pub par : i64,
pub lateUs : i64,
pub homes : i32,
constructor(emptyUs : i64, worstUs : i64, busyUs : i64, par : i64, lateUs : i64, homes : i32) {
self.emptyUs = emptyUs;
self.worstUs = worstUs;
self.busyUs = busyUs;
self.par = par;
self.lateUs = lateUs;
self.homes = homes;
}
}
class Crew {
pub begin : Semaphore = new Semaphore(0),
pub ended : Semaphore = new Semaphore(0),
pub ticket : AtomicI32 = new AtomicI32(0),
pub work : AtomicI32 = new AtomicI32(0),
pub alive : AtomicBoolean = new AtomicBoolean(true),
pub spins : i32,
pub home : i32[],
pub t0 : i64[],
pub t1 : i64[],
pub sink : i64[],
constructor(spins : i32) {
self.spins = spins;
self.home = new i32[SHARES];
self.t0 = new i64[SHARES];
self.t1 = new i64[SHARES];
self.sink = new i64[SHARES];
}
}
fn takePermit(s : Semaphore, spins : i32) : void {
for (i of 0..spins) {
if (s.tryAcquire()) {
return;
}
}
let mut got : bool = false;
while (!got) {
try {
s.acquire();
got = true;
} catch e : InterruptedException {
got = false;
}
}
}
fn runShare(mut c : Crew, share : i32) : void {
c.t0[share] = monotonicNanos();
let mut acc : i64 = 0;
for (i of 0..c.work.get()) {
acc = acc + ((i as i64) * 7) % 13;
}
c.sink[share] = acc;
c.t1[share] = monotonicNanos();
}
fn crewLoop(mut c : Crew, me : i32) : i32 {
c.home[me] = osThread();
while (true) {
takePermit(c.begin, c.spins);
if (!c.alive.get()) {
return 0;
}
runShare(c, c.ticket.incrementAndGet());
c.ended.release();
}
return 0;
}
fn pass(mut c : Crew, work : i32) : void {
c.work.set(work);
c.ticket.set(0);
for (i of 0..(SHARES - 1)) {
c.begin.release();
}
runShare(c, 0);
for (i of 0..(SHARES - 1)) {
takePermit(c.ended, c.spins);
}
}
fn distinctHomes(c : Crew) : i32 {
let mut n : i32 = 0;
for (k of 0..(SHARES - 1)) {
let mut seen : bool = false;
for (j of 0..k) {
if (c.home[j] == c.home[k]) {
seen = true;
}
}
if (!seen) {
n = n + 1;
}
}
return n;
}
fn measure(kind : string, spins : i32) : Report ! IllegalStateException {
let c : Crew = new Crew(spins);
let mut threads : Thread[11];
let mut tasks : Future<i32>[11];
for (i of 0..(SHARES - 1)) {
if (kind == "thread") {
threads[i] = Thread::run(crewLoop, c, i);
} else {
tasks[i] = spawn crewLoop(c, i);
}
}
for (w of 0..20) {
pass(c, 0);
}
let e0 : i64 = monotonicNanos();
let mut worst : i64 = 0;
for (r of 0..EMPTY_PASSES) {
let s : i64 = monotonicNanos();
pass(c, 0);
let d : i64 = monotonicNanos() - s;
if (d > worst) {
worst = d;
}
}
let emptyUs : i64 = (monotonicNanos() - e0) / (EMPTY_PASSES as i64) / 1000;
let b0 : i64 = monotonicNanos();
let mut parSum : i64 = 0;
let mut lagSum : i64 = 0;
for (r of 0..BUSY_PASSES) {
pass(c, SHARE_STEPS);
let seen : i64 = monotonicNanos();
let mut first : i64 = c.t0[0];
let mut last : i64 = c.t1[0];
let mut busy : i64 = 0;
for (k of 0..SHARES) {
busy = busy + (c.t1[k] - c.t0[k]);
if (c.t0[k] < first) {
first = c.t0[k];
}
if (c.t1[k] > last) {
last = c.t1[k];
}
}
parSum = parSum + (busy * 100) / (last - first);
lagSum = lagSum + (seen - last);
}
let busyUs : i64 = (monotonicNanos() - b0) / (BUSY_PASSES as i64) / 1000;
let par : i64 = parSum / (BUSY_PASSES as i64);
let report : Report = new Report(
emptyUs,
worst / 1000,
busyUs,
par,
lagSum / (BUSY_PASSES as i64) / 1000,
distinctHomes(c));
c.alive.set(false);
for (i of 0..(SHARES - 1)) {
c.begin.release();
}
for (i of 0..(SHARES - 1)) {
if (kind == "thread") {
threads[i].join();
} else {
let d : i32 = await tasks[i];
}
}
return report;
}
fn show(kind : string, spins : i32, r : Report) : void {
println("${kind} spins=${spins}: empty ${r.emptyUs} us (worst ${r.worstUs})"
+ " | loaded ${r.busyUs} us, x${r.par / 100}.${r.par % 100} at once,"
+ " caller sees the end +${r.lateUs} us"
+ " | workers on ${r.homes}/11 OS threads");
}
fn below(what : string, got : i64, limit : i64) : i32 {
if (got < limit) {
return 0;
}
println("FAIL ${what}: ${got} us, limit ${limit} us");
return 1;
}
fn threadsWanted() : i32 {
let mut wanted : i32 = cpuCount() - 1;
if (wanted > SHARES - 1) {
wanted = SHARES - 1;
}
if (wanted < 1) {
wanted = 1;
}
return wanted;
}
fn check() : i32 ! IllegalStateException {
let mut failed : i32 = 0;
let t : Report = measure("thread", 0);
show("thread", 0, t);
failed = failed + below("thread empty fan-out", t.emptyUs, EMPTY_LIMIT_US);
failed = failed + below("thread loaded pass", t.busyUs, LOADED_LIMIT_US);
failed = failed + below("thread caller late", t.lateUs, LATE_LIMIT_US);
let k : Report = measure("task", 0);
show("task", 0, k);
failed = failed + below("task empty fan-out", k.emptyUs, EMPTY_LIMIT_US);
failed = failed + below("task loaded pass", k.busyUs, LOADED_LIMIT_US);
failed = failed + below("task caller late", k.lateUs, LATE_LIMIT_US);
if (k.homes < threadsWanted()) {
println("FAIL task crew on ${k.homes} OS threads, wanted ${threadsWanted()}");
failed = failed + 1;
}
if (failed > 0) {
return 1;
}
println("crew_fanout check: every limit held");
return 0;
}
fn arg(i : i32) : string {
try {
return argAt(i);
} catch e : IndexOutOfBoundsException {
return "";
}
}
fn argInt(i : i32) : i32 {
try {
return arg(i).toI64() as i32;
} catch e : ParseException {
return 0;
}
}
fn hasWord(word : string) : bool {
for (i of 1..4) {
if (arg(i) == word) {
return true;
}
}
return false;
}
fn variant(kind : string, spins : i32) : void ! IllegalStateException {
show(kind, spins, measure(kind, spins));
}
fn main() : i32 ! IllegalStateException {
if (hasWord("fine")) {
fineTimer();
}
if (arg(1) == "check") {
return check();
}
if (arg(1) == "thread" || arg(1) == "task") {
variant(arg(1), argInt(2));
return 0;
}
variant("thread", 0);
variant("task", 0);
variant("thread", 20000);
variant("task", 20000);
return 0;
}The same 256M-step integer chain split over 32 spawned tasks — one measurement per carrier-pool width. Set AXLE_CARRIERS to 1, 2, 4, 8 and the machine default, and read wall(N)/wall(1) against N; that ratio is what sizes the pool. Do not pass --pin: it parks the process on a single core, which is what this benchmark measures the absence of. Each task never awaits, so it holds its carrier for its whole life and the reading is the pool, not the scheduler.
| Variant | Run | Compile | Output | ||
|---|---|---|---|---|---|
| Run time | RAM | Compile time | RAM | Binary | |
| Axle -O2 | 6 ms | 44.5 MB | 93 ms | 126.6 MB | 472 KB |
| Axle -O3 | 6 ms | 44.5 MB | 93 ms | 123.0 MB | 472 KB |
| Axle -O1 | 33 ms | 44.5 MB | 86 ms | 122.9 MB | 472 KB |
| Axle -O0 | 69 ms | 44.5 MB | 73 ms | 123.7 MB | 474 KB |
// EXPECTED_EXIT: 0
// Fan-out scaling — one integer workload split over 32 spawned tasks, run at
// several carrier-pool widths.
//
// The workload is deliberately uniform: 32 tasks, each walking the same
// 8,000,000-step LCG chain and returning its final state, for 256,000,000
// steps in total. Every task is independent, non-blocking arithmetic, so
// wall(N)/wall(1) reads the pool and nothing else — there is no lock, no
// channel and no I/O for a wider pool to spend its time on instead of the
// work. The tasks are spawned before the first await and never await
// themselves, so they occupy their carriers for their whole life.
//
// Read it with AXLE_CARRIERS set to 1, 2, 4, 8 and then unset (the machine
// default); the ratio against N is what decides the pool's size. Do not pass
// --pin: pinning the process to one core measures the absence of the thing
// this benchmark is about.
//
// The total is printed so that a mis-split workload is visible without a
// profiler.
fn chain(steps : i64) : i64 {
let mut x : i64 = 1;
let mut i : i64 = 0;
while (i < steps) {
x = x * 6364136223846793005 + 1442695040888963407;
i = i + 1;
}
return x;
}
fn main() : i32 {
let steps : i64 = 8000000;
let fs : Future<i64>[] = [
spawn chain(steps), spawn chain(steps), spawn chain(steps),
spawn chain(steps), spawn chain(steps), spawn chain(steps),
spawn chain(steps), spawn chain(steps), spawn chain(steps),
spawn chain(steps), spawn chain(steps), spawn chain(steps),
spawn chain(steps), spawn chain(steps), spawn chain(steps),
spawn chain(steps), spawn chain(steps), spawn chain(steps),
spawn chain(steps), spawn chain(steps), spawn chain(steps),
spawn chain(steps), spawn chain(steps), spawn chain(steps),
spawn chain(steps), spawn chain(steps), spawn chain(steps),
spawn chain(steps), spawn chain(steps), spawn chain(steps),
spawn chain(steps), spawn chain(steps),
];
let mut total : i64 = 0;
let mut k : i32 = 0;
while (k < 32) {
total = total + await fs[k];
k = k + 1;
}
println(total);
return 0;
}50,000 spawn/await round trips, one task at a time, each body three arithmetic operations — so the number is the hand-off itself: publish, park, a carrier takes it, the result is routed home, resume. Latency-bound by construction; the difference between AXLE_CARRIERS=1 and the machine default is what a second carrier buys on that round trip.
| Variant | Run | Compile | Output | ||
|---|---|---|---|---|---|
| Run time | RAM | Compile time | RAM | Binary | |
| Axle -O3 | 169 ms | 45.3 MB | 77 ms | 123.2 MB | 469 KB |
| Axle -O0 | 170 ms | 45.3 MB | 69 ms | 123.5 MB | 469 KB |
| Axle -O2 | 170 ms | 45.3 MB | 76 ms | 121.6 MB | 469 KB |
| Axle -O1 | 172 ms | 45.3 MB | 75 ms | 123.4 MB | 469 KB |
// EXPECTED_EXIT: 0
// spawn/await round-trip latency — 50,000 trips, one task in flight at a time.
//
// The body is three arithmetic operations, so the measurement is the hand-off
// itself and not the work: publish the block to the injector, park the
// spawning frame, a carrier takes it, the result is routed home, resume. The
// tasks are serialised on purpose — one outstanding at a time — because what
// this isolates is the cost a single round trip pays, which a fan-out would
// hide behind the pool's width.
//
// Read the difference between AXLE_CARRIERS=1 and the machine default: that is
// what a second carrier buys on a round trip that never blocks.
//
// The checksum is printed so that a round trip that returned the wrong result
// is visible without a profiler.
fn work(x : i64) : i64 {
return x * 3 + 1 + x;
}
fn main() : i32 {
let rounds : i64 = 50000;
let mut acc : i64 = 0;
let mut i : i64 = 0;
while (i < rounds) {
let f : Future<i64> = spawn work(i);
acc = acc + await f;
i = i + 1;
}
println(acc);
return 0;
}The per-frame fork/join: N jobs spawned back to back, the caller's own share, then an await per job, with every job the length of the share. Run by hand: it prints when each job started against the caller's share, and its `check` mode fails when a job of a 5-job burst waits for a carrier that was busy while idle ones were free.
| Variant | Run | Compile | Output | ||
|---|---|---|---|---|---|
| Run time | RAM | Compile time | RAM | Binary | |
| Axle -O3 | 4.22 s | 44.5 MB | 194 ms | 129.7 MB | 488 KB |
| Axle -O2 | 4.22 s | 44.5 MB | 182 ms | 124.8 MB | 488 KB |
| Axle -O1 | 11.36 s | 44.5 MB | 142 ms | 126.3 MB | 486 KB |
| Axle -O0 | 26.22 s | 44.5 MB | 93 ms | 125.7 MB | 493 KB |
// EXPECTED_EXIT: 0
// Spawn burst — the per-frame fork/join: the caller spawns N jobs back to
// back, computes its own share, then awaits each job. Every job and the
// caller's share are the same length, and the pool has more idle carriers than
// there are jobs, so every job should start within microseconds of its spawn
// and the round should last about one share.
//
// spawn_burst the diagnostic matrix (below)
// spawn_burst <jobs> [gap_us] one line: N jobs, gap_us between spawns
// spawn_burst check 5 jobs, no gap; exit 1 on a miss
//
// The matrix is 1, 3, 5 and 8 jobs spawned back to back, then 5 jobs with 5 us
// and 10 us of busy-waiting between two spawns. Per line, over ROUNDS rounds:
// the mean round against the mean share, when the first and the last job
// started relative to the round's start, how many jobs started only after the
// caller's own share had ended — a job no carrier took while the caller was
// busy — and, of those, how many ran on an OS thread that had already run a job
// of the same round: a late job queued behind another job on one carrier.
//
// `check` fails when any job of a 5-job burst starts after the caller's share,
// or when the mean round exceeds ROUND_LIMIT_PCT percent of the mean share. As
// for crew_fanout, a time on a shared runner is not a fact: run by hand, on a
// quiet machine, not in CI.
use std::lang::{ IndexOutOfBoundsException, ParseException };
use std::sys::process::{ argAt };
use std::time::monotonicNanos;
@target(os = windows)
extern "C" fn GetCurrentThreadId() : i32;
@target(os = linux)
extern "C" fn gettid() : i32;
@target(os = windows)
fn osThread() : i32 {
return GetCurrentThreadId();
}
@target(os = linux)
fn osThread() : i32 {
return gettid();
}
const ROUNDS : i32 = 300;
const WARMUP : i32 = 20;
const MAX_JOBS : i32 = 8;
const SHARE_STEPS : i32 = 4000000;
const ROUND_LIMIT_PCT : i64 = 160;
class Round {
pub start : i64[],
pub tid : i32[],
pub sink : i64[],
constructor() {
self.start = new i64[MAX_JOBS + 1];
self.tid = new i32[MAX_JOBS + 1];
self.sink = new i64[MAX_JOBS + 1];
}
}
fn job(mut r : Round, k : i32) : i32 {
r.start[k] = monotonicNanos();
r.tid[k] = osThread();
let mut acc : i64 = 0;
for (i of 0..SHARE_STEPS) {
acc = acc + ((i as i64) * 7) % 13;
}
r.sink[k] = acc;
return 0;
}
struct Burst {
roundUs : i64,
shareUs : i64,
firstUs : i64,
lastUs : i64,
late : i32,
lateQueued : i32,
jobs : i32,
}
fn measure(jobs : i32, gapUs : i32) : Burst {
let r : Round = new Round();
let mut fs : Future<i32>[8];
let mut total : i64 = 0;
let mut share : i64 = 0;
let mut first : i64 = 0;
let mut last : i64 = 0;
let mut late : i32 = 0;
let mut lateQueued : i32 = 0;
for (round of 0..(WARMUP + ROUNDS)) {
let s : i64 = monotonicNanos();
for (k of 0..jobs) {
fs[k] = spawn job(r, k + 1);
let until : i64 = monotonicNanos() + (gapUs as i64) * 1000;
while (monotonicNanos() < until) {
}
}
let m0 : i64 = monotonicNanos();
let mine : i32 = job(r, 0);
let m1 : i64 = monotonicNanos();
for (k of 0..jobs) {
let d : i32 = await fs[k];
}
let e : i64 = monotonicNanos();
if (round < WARMUP) {
continue;
}
let mut lo : i64 = r.start[1];
let mut hi : i64 = r.start[1];
for (k of 1..(jobs + 1)) {
if (r.start[k] < lo) {
lo = r.start[k];
}
if (r.start[k] > hi) {
hi = r.start[k];
}
if (r.start[k] >= m1) {
late = late + 1;
for (j of 1..(jobs + 1)) {
if (j != k && r.tid[j] == r.tid[k] && r.start[j] < r.start[k]) {
lateQueued = lateQueued + 1;
break;
}
}
}
}
total = total + (e - s);
share = share + (m1 - m0);
first = first + (lo - s);
last = last + (hi - s);
}
let n : i64 = (ROUNDS as i64) * 1000;
return Burst {
roundUs: total / n,
shareUs: share / n,
firstUs: first / n,
lastUs: last / n,
late: late,
lateQueued: lateQueued,
jobs: jobs,
};
}
fn report(b : Burst, gapUs : i32) : void {
println("${b.jobs} jobs, gap ${gapUs} us: round ${b.roundUs} us for a share of ${b.shareUs} us"
+ " | jobs start: first +${b.firstUs}, last +${b.lastUs} us"
+ " | ${b.late} of ${ROUNDS * b.jobs} started after the caller's share"
+ ", ${b.lateQueued} of them behind a job of the same round on the same OS thread");
}
fn check() : i32 {
let b : Burst = measure(5, 0);
report(b, 0);
let mut fails : i32 = 0;
if (b.late > 0) {
println("FAIL ${b.late} jobs started after the caller's own share, limit 0");
fails = fails + 1;
}
if (b.roundUs * 100 > b.shareUs * ROUND_LIMIT_PCT) {
println("FAIL round ${b.roundUs} us is over ${ROUND_LIMIT_PCT}% of the share (${b.shareUs} us)");
fails = fails + 1;
}
if (fails > 0) {
return 1;
}
println("spawn_burst check: every limit held");
return 0;
}
fn arg(i : i32) : string {
try {
return argAt(i);
} catch e : IndexOutOfBoundsException {
return "";
}
}
fn argInt(i : i32, fallback : i32) : i32 {
try {
return argAt(i).toI64() as i32;
} catch e : IndexOutOfBoundsException {
return fallback;
} catch e : ParseException {
return fallback;
}
}
fn main() : i32 {
if (arg(1) == "check") {
return check();
}
let one : i32 = argInt(1, 0);
if (one > 0) {
let jobs : i32 = one.min(MAX_JOBS);
let gap : i32 = argInt(2, 0);
report(measure(jobs, gap), gap);
return 0;
}
report(measure(1, 0), 0);
report(measure(3, 0), 0);
report(measure(5, 0), 0);
report(measure(8, 0), 0);
report(measure(5, 5), 5);
report(measure(5, 10), 10);
return 0;
}Where an empty fan-out's time goes, one hop at a time: eleven workers parked on one semaphore, released and collected by the caller. Run by hand with AXLE_CARRIERS swept — a wake whose cost grows with the pool is a wake that reaches every carrier.
| Variant | Run | Compile | Output | ||
|---|---|---|---|---|---|
| Run time | RAM | Compile time | RAM | Binary | |
| Axle -O3 | 59 ms | 43.7 MB | 175 ms | 125.5 MB | 503 KB |
| Axle -O0 | 60 ms | 43.7 MB | 94 ms | 125.8 MB | 511 KB |
| Axle -O1 | 60 ms | 43.7 MB | 117 ms | 128.3 MB | 500 KB |
| Axle -O2 | 60 ms | 43.7 MB | 150 ms | 128.2 MB | 501 KB |
// EXPECTED_EXIT: 0
// Wake hops — where an empty fan-out's time goes, one hop at a time.
//
// wake_hops both variants
// wake_hops <thread|task> one variant
//
// Eleven workers park on one semaphore; `main` releases it eleven times and
// collects eleven releases of another. Over 1000 empty passes it prints, as
// means relative to the pass start: how long `main`'s eleven releases took,
// when the first, median and last worker came out of its acquire, when the
// last worker had released, and how long after that `main` was back.
//
// thread : the workers are Thread::run bodies — plain frames on the wait list.
// task : the workers are spawned tasks — parked tasks on the wait list.
//
// Read it with AXLE_CARRIERS swept (12, 16, the default, 32, 48): a wake whose
// cost grows with the number of carriers is a wake that reaches all of them.
// The workers start in a burst and never run long, so this measures the wake
// path and nothing else; crew_fanout is the same crew with work in it.
use std::concurrent::{ AtomicBoolean, AtomicI32, Semaphore, Thread };
use std::lang::{ IllegalStateException, InterruptedException, IndexOutOfBoundsException };
use std::sys::process::{ argAt };
use std::time::monotonicNanos;
const WORKERS : i32 = 11;
const WARMUP : i32 = 100;
const PASSES : i32 = 1000;
class Crew {
pub begin : Semaphore = new Semaphore(0),
pub ended : Semaphore = new Semaphore(0),
pub ticket : AtomicI32 = new AtomicI32(0),
pub alive : AtomicBoolean = new AtomicBoolean(true),
pub woke : i64[],
pub done : i64[],
constructor() {
self.woke = new i64[WORKERS];
self.done = new i64[WORKERS];
}
}
fn take(s : Semaphore) : void {
let mut got : bool = false;
while (!got) {
try {
s.acquire();
got = true;
} catch e : InterruptedException {
got = false;
}
}
}
fn crewLoop(mut c : Crew) : i32 {
while (true) {
take(c.begin);
let now : i64 = monotonicNanos();
if (!c.alive.get()) {
return 0;
}
let k : i32 = c.ticket.incrementAndGet() - 1;
c.woke[k] = now;
c.done[k] = monotonicNanos();
c.ended.release();
}
return 0;
}
fn sortInPlace(mut a : i64[], n : i32) : void {
for (i of 1..n) {
let v : i64 = a[i];
let mut j : i32 = i - 1;
while (j >= 0 && a[j] > v) {
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = v;
}
}
fn measure(kind : string) : void ! IllegalStateException {
let c : Crew = new Crew();
let mut threads : Thread[11];
let mut tasks : Future<i32>[11];
for (i of 0..WORKERS) {
if (kind == "thread") {
threads[i] = Thread::run(crewLoop, c);
} else {
tasks[i] = spawn crewLoop(c);
}
}
let mut released : i64 = 0;
let mut first : i64 = 0;
let mut median : i64 = 0;
let mut last : i64 = 0;
let mut lastDone : i64 = 0;
let mut back : i64 = 0;
let mut order : i64[] = new i64[WORKERS];
for (p of 0..(WARMUP + PASSES)) {
c.ticket.set(0);
let s : i64 = monotonicNanos();
for (i of 0..WORKERS) {
c.begin.release();
}
let r : i64 = monotonicNanos();
for (i of 0..WORKERS) {
take(c.ended);
}
let e : i64 = monotonicNanos();
if (p >= WARMUP) {
let mut latestDone : i64 = c.done[0];
for (k of 0..WORKERS) {
order[k] = c.woke[k] - s;
if (c.done[k] > latestDone) {
latestDone = c.done[k];
}
}
sortInPlace(order, WORKERS);
released = released + (r - s);
first = first + order[0];
median = median + order[WORKERS / 2];
last = last + order[WORKERS - 1];
lastDone = lastDone + (latestDone - s);
back = back + (e - latestDone);
}
}
let n : i64 = (PASSES as i64) * 1000;
println("${kind}: 11 releases take ${released / n} us | workers wake: first +${first / n}, median +${median / n}, last +${last / n} us"
+ " | last worker done +${lastDone / n} us | main back ${back / n} us after it");
c.alive.set(false);
for (i of 0..WORKERS) {
c.begin.release();
}
for (i of 0..WORKERS) {
if (kind == "thread") {
threads[i].join();
} else {
let d : i32 = await tasks[i];
}
}
}
fn arg(i : i32) : string {
try {
return argAt(i);
} catch e : IndexOutOfBoundsException {
return "";
}
}
fn main() : i32 ! IllegalStateException {
if (arg(1) == "thread" || arg(1) == "task") {
measure(arg(1));
return 0;
}
measure("thread");
measure("task");
return 0;
}