<!-- Benchmarks · Tin · https://tin.ad/docs/bench/ · generated from the built page -->

# Benchmarks

9 small programs, each written in Tin, JavaScript, Python and Rust with the same algorithm.
The harness refuses to record a result if the four outputs differ. Every number here is read from
`bench/results/latest.json` when the site is built.

## How to read it

- Rust is fastest on 7 of 8: it compiles ahead of time with no runtime, and every Tin integer
`+ - *` is overflow-checked and every index bounds-checked.

- Tin beats Python on 8 of 8 and JavaScript on 4 of 8. On Node, Tin and JavaScript share
an engine, so number crunching lands close; Tin pays a fixed cost to load its runtime (see `hello`).

- Without Node, `tin build --native` beats JavaScript on 7 of 7 in time
and 7 of 7 in memory, ties or beats Rust on 3, and is within 2× of Rust on 7
([table](#no-node)). It refuses `agent`: agents and tasks need the JavaScript host.

- `sort` is not like-for-like: Tin sorts `int[]` with a radix sort, the others compare.
`sortBy` compares, so it is the fair row.

- Tin loses to JavaScript or Python on `agent`, `mandelbrot`, `nbody`, `trees`
(computed from the data). `agent`: the two sides run different models; Tin's offline `mock` also
estimates tokens and fills tool input from its schema. With the JavaScript loop's model inside Tin's runtime:
52.5 ms against 47 ms (`bench/agent-parts.mjs`). `trees`: Tin frees each node the moment it dies; JavaScript frees young objects in bulk, with 4× the memory.
`nbody`: every `b.x[i]` is bounds-checked.

## Run time

Whole process, median of 7 runs, ms. Lower is better; the fastest per row is bold.

| program | Tin | JavaScript | Python | Rust |
| --- | --- | --- | --- | --- |
| hello | 26 ms | 24 ms | 14 ms | 3.2 ms |
| agent | 112 ms | 72 ms | 184 ms | 32 ms |
| fib | 53 ms | 99 ms | 667 ms | 25 ms |
| mandelbrot | 72 ms | 69 ms | 1.22 s | 45 ms |
| nbody | 55 ms | 47 ms | 1.13 s | 14 ms |
| sieve | 78 ms | 96 ms | 1.62 s | 20 ms |
| sort | 74 ms | 366 ms | 834 ms | 35 ms |
| trees | 128 ms | 122 ms | 758 ms | 276 ms |
| words | 109 ms | 177 ms | 314 ms | 46 ms |

## Without Node

Whole process, median. Tin WASI is `tin build --target wasi` under wasmtime 50.0.1;
Tin native is `tin build --native` (wasm2c, then Apple clang version 21.0.0 -O2). Both keep every check. — means refused.

| program | Tin on Node | Tin WASI | Tin native | JavaScript | Rust |
| --- | --- | --- | --- | --- | --- |
| hello | 26 ms | 5.3 ms | 2.9 ms | 24 ms | 3.2 ms |
| agent | 112 ms | — | — | 72 ms | 32 ms |
| fib | 53 ms | 76 ms | 36 ms | 99 ms | 25 ms |
| mandelbrot | 72 ms | 52 ms | 44 ms | 69 ms | 45 ms |
| nbody | 55 ms | 57 ms | 21 ms | 47 ms | 14 ms |
| sieve | 78 ms | 33 ms | 25 ms | 96 ms | 20 ms |
| sort | 74 ms | 41 ms | 28 ms | 366 ms | 35 ms |
| trees | 128 ms | 166 ms | 103 ms | 122 ms | 276 ms |
| words | 109 ms | 94 ms | 58 ms | 177 ms | 46 ms |

## Peak memory

Largest resident set over the runs, MB. Tin and JavaScript include Node itself.

| program | Tin | JavaScript | Python | Rust |
| --- | --- | --- | --- | --- |
| hello | 55 | 53 | 18 | 2 |
| agent | 81 | 71 | 20 | 3 |
| fib | 58 | 57 | 18 | 2 |
| mandelbrot | 58 | 60 | 18 | 2 |
| nbody | 58 | 60 | 19 | 2 |
| sieve | 68 | 134 | 95 | 12 |
| sort | 97 | 139 | 124 | 27 |
| trees | 67 | 107 | 26 | 10 |
| words | 142 | 212 | 135 | 49 |

**Ranges, run time inside the process, compile time

Min–max of the whole-process runs, ms.

| program | Tin | JavaScript | Python | Rust |
| --- | --- | --- | --- | --- |
| hello | 26 ms–28 ms | 24 ms–26 ms | 14 ms–14 ms | 3.1 ms–3.5 ms |
| agent | 111 ms–114 ms | 71 ms–74 ms | 183 ms–188 ms | 30 ms–34 ms |
| fib | 52 ms–54 ms | 98 ms–100 ms | 663 ms–676 ms | 25 ms–26 ms |
| mandelbrot | 70 ms–76 ms | 69 ms–71 ms | 1.21 s–1.25 s | 45 ms–47 ms |
| nbody | 54 ms–58 ms | 46 ms–47 ms | 1.12 s–1.14 s | 13 ms–14 ms |
| sieve | 75 ms–82 ms | 94 ms–104 ms | 1.60 s–1.72 s | 19 ms–21 ms |
| sort | 73 ms–77 ms | 364 ms–375 ms | 825 ms–842 ms | 34 ms–36 ms |
| trees | 127 ms–130 ms | 121 ms–123 ms | 755 ms–773 ms | 267 ms–290 ms |
| words | 108 ms–114 ms | 176 ms–185 ms | 305 ms–320 ms | 45 ms–47 ms |

Inside the process (load + compile + run, no interpreter or Node startup), median. Rust's process starts in about 3.2 ms.

| program | Tin | JavaScript | Python |
| --- | --- | --- | --- |
| hello | 2.2 ms | 1.5 ms | 1.6 ms |
| agent | 86 ms | 47 ms | 171 ms |
| fib | 28 ms | 75 ms | 654 ms |
| mandelbrot | 46 ms | 45 ms | 1.21 s |
| nbody | 30 ms | 22 ms | 1.12 s |
| sieve | 50 ms | 71 ms | 1.60 s |
| sort | 49 ms | 341 ms | 751 ms |
| trees | 103 ms | 96 ms | 745 ms |
| words | 84 ms | 149 ms | 294 ms |

Compile time, median. Python and JavaScript compile as they run.

| program | `tin build` | `rustc -C opt-level=3` |
| --- | --- | --- |
| hello | 44 ms | 73 ms |
| agent | 49 ms | 207 ms |
| fib | 45 ms | 76 ms |
| mandelbrot | 46 ms | 79 ms |
| nbody | 49 ms | 112 ms |
| sieve | 47 ms | 86 ms |
| sort | 50 ms | 148 ms |
| trees | 47 ms | 85 ms |
| words | 53 ms | 182 ms |

## Race it in your browser

The same program in Tin (WebAssembly) and JavaScript, each in its own worker, timed on your machine now.

Program  fib mandelbrot nbody sieve  Python too (Pyodide, about 10 MB, once)  one at a time  Recursive Fibonacci: function-call overhead.

Tin WebAssembly — ready

JavaScript your JS engine — ready

Python Pyodide 0.29.5 — ready

<!-- output -->
```text

```

 Native, from the table above: . Tin compiled when this site was built; JavaScript's parse and JIT are inside its time; Pyodide's download is not.

**The three sources

Tin

```tin
// Recursive Fibonacci: function-call overhead.
fn fib(n: int): int => if n < 2 { n } else { fib(n - 1) + fib(n - 2) }

fn main() {
  print("fib(36) = {fib(36)}")
}
```

 JavaScript

```tin
// Recursive Fibonacci: function-call overhead.
function fib(n) {
  return n < 2 ? n : fib(n - 1) + fib(n - 2)
}

console.log(`fib(36) = ${fib(36)}`)
```

 Python

```tin
# Recursive Fibonacci: function-call overhead.
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(f"fib(36) = {fib(36)}")
```

Tin

```tin
// Mandelbrot set: floating-point arithmetic in nested loops.
fn escape(cr: float, ci: float, limit: int): int {
  var zr = 0.0
  var zi = 0.0
  var i = 0
  while i < limit && zr * zr + zi * zi <= 4.0 {
    let next = zr * zr - zi * zi + cr
    zi = 2.0 * zr * zi + ci
    zr = next
    i += 1
  }
  i
}

fn main() {
  let size = 800
  var total = 0
  var inside = 0
  for row in 0..size {
    for col in 0..size {
      let x = float(col) / float(size) * 3.0 - 2.0
      let y = float(row) / float(size) * 3.0 - 1.5
      let n = escape(x, y, 200)
      total += n
      if n == 200 { inside += 1 }
    }
  }
  print("{size}x{size}: {inside} points inside, {total} iterations")
}
```

 JavaScript

```tin
// Mandelbrot set: floating-point arithmetic in nested loops.
function escape(cr, ci, limit) {
  let zr = 0.0, zi = 0.0, i = 0
  while (i < limit && zr * zr + zi * zi <= 4.0) {
    const next = zr * zr - zi * zi + cr
    zi = 2.0 * zr * zi + ci
    zr = next
    i++
  }
  return i
}

const size = 800
let total = 0, inside = 0
for (let row = 0; row < size; row++) {
  for (let col = 0; col < size; col++) {
    const x = col / size * 3.0 - 2.0
    const y = row / size * 3.0 - 1.5
    const n = escape(x, y, 200)
    total += n
    if (n === 200) inside++
  }
}
console.log(`${size}x${size}: ${inside} points inside, ${total} iterations`)
```

 Python

```tin
# Mandelbrot set: floating-point arithmetic in nested loops.
def escape(cr, ci, limit):
    zr = 0.0
    zi = 0.0
    i = 0
    while i < limit and zr * zr + zi * zi <= 4.0:
        nxt = zr * zr - zi * zi + cr
        zi = 2.0 * zr * zi + ci
        zr = nxt
        i += 1
    return i

size = 800
total = 0
inside = 0
for row in range(size):
    for col in range(size):
        x = col / size * 3.0 - 2.0
        y = row / size * 3.0 - 1.5
        n = escape(x, y, 200)
        total += n
        if n == 200:
            inside += 1
print(f"{size}x{size}: {inside} points inside, {total} iterations")
```

Tin

```tin
// N-body: the Jovian planets, a float-heavy simulation over arrays.
let SOLAR_MASS = 39.47841760435743  // 4 * pi * pi
let DAYS = 365.24

type Bodies = { x: float[], y: float[], z: float[], vx: float[], vy: float[], vz: float[], m: float[] }

fn bodies(): Bodies {
  var b = Bodies {
    x: [0.0, 4.84143144246472090e+00, 8.34336671824457987e+00, 1.28943695621391310e+01, 1.53796971148509165e+01],
    y: [0.0, -1.16032004402742839e+00, 4.12479856412430479e+00, -1.51111514016986312e+01, -2.59193146099879641e+01],
    z: [0.0, -1.03622044471123109e-01, -4.03523417114321381e-01, -2.23307578892655734e-01, 1.79258772950371181e-01],
    vx: [0.0, 1.66007664274403694e-03 * DAYS, -2.76742510726862411e-03 * DAYS, 2.96460137564761618e-03 * DAYS, 2.68067772490389322e-03 * DAYS],
    vy: [0.0, 7.69901118419740425e-03 * DAYS, 4.99852801234917238e-03 * DAYS, 2.37847173959480950e-03 * DAYS, 1.62824170038242295e-03 * DAYS],
    vz: [0.0, -6.90460016972063023e-05 * DAYS, 2.30417297573763929e-05 * DAYS, -2.96589568540237556e-05 * DAYS, -9.51592254519715870e-05 * DAYS],
    m: [SOLAR_MASS, 9.54791938424326609e-04 * SOLAR_MASS, 2.85885980666130812e-04 * SOLAR_MASS, 4.36624404335156298e-05 * SOLAR_MASS, 5.15138902046611451e-05 * SOLAR_MASS],
  }
  // offset the sun's momentum so the system's total is zero
  var px = 0.0
  var py = 0.0
  var pz = 0.0
  for i in 0..5 {
    px += b.vx[i] * b.m[i]
    py += b.vy[i] * b.m[i]
    pz += b.vz[i] * b.m[i]
  }
  b.vx[0] = 0.0 - px / SOLAR_MASS
  b.vy[0] = 0.0 - py / SOLAR_MASS
  b.vz[0] = 0.0 - pz / SOLAR_MASS
  b
}

fn energy(b: Bodies): float {
  var e = 0.0
  for i in 0..5 {
    e += 0.5 * b.m[i] * (b.vx[i] * b.vx[i] + b.vy[i] * b.vy[i] + b.vz[i] * b.vz[i])
    for j in i + 1..5 {
      let dx = b.x[i] - b.x[j]
      let dy = b.y[i] - b.y[j]
      let dz = b.z[i] - b.z[j]
      e -= b.m[i] * b.m[j] / sqrt(dx * dx + dy * dy + dz * dz)
    }
  }
  e
}

fn advance(b: inout Bodies, dt: float) {
  for i in 0..5 {
    for j in i + 1..5 {
      let dx = b.x[i] - b.x[j]
      let dy = b.y[i] - b.y[j]
      let dz = b.z[i] - b.z[j]
      let d2 = dx * dx + dy * dy + dz * dz
      let mag = dt / (d2 * sqrt(d2))
      let mi = b.m[i] * mag
      let mj = b.m[j] * mag
      b.vx[i] -= dx * mj
      b.vy[i] -= dy * mj
      b.vz[i] -= dz * mj
      b.vx[j] += dx * mi
      b.vy[j] += dy * mi
      b.vz[j] += dz * mi
    }
  }
  for i in 0..5 {
    b.x[i] += dt * b.vx[i]
    b.y[i] += dt * b.vy[i]
    b.z[i] += dt * b.vz[i]
  }
}

fn main() {
  var b = bodies()
  print(energy(b).fixed(9))
  for step in 0..500000 { advance(&b, 0.01) }
  print(energy(b).fixed(9))
}
```

 JavaScript

```tin
// N-body: the Jovian planets, a float-heavy simulation over arrays.
const SOLAR_MASS = 39.47841760435743 // 4 * pi * pi
const DAYS = 365.24

function bodies() {
  const b = {
    x: [0.0, 4.84143144246472090e+00, 8.34336671824457987e+00, 1.28943695621391310e+01, 1.53796971148509165e+01],
    y: [0.0, -1.16032004402742839e+00, 4.12479856412430479e+00, -1.51111514016986312e+01, -2.59193146099879641e+01],
    z: [0.0, -1.03622044471123109e-01, -4.03523417114321381e-01, -2.23307578892655734e-01, 1.79258772950371181e-01],
    vx: [0.0, 1.66007664274403694e-03 * DAYS, -2.76742510726862411e-03 * DAYS, 2.96460137564761618e-03 * DAYS, 2.68067772490389322e-03 * DAYS],
    vy: [0.0, 7.69901118419740425e-03 * DAYS, 4.99852801234917238e-03 * DAYS, 2.37847173959480950e-03 * DAYS, 1.62824170038242295e-03 * DAYS],
    vz: [0.0, -6.90460016972063023e-05 * DAYS, 2.30417297573763929e-05 * DAYS, -2.96589568540237556e-05 * DAYS, -9.51592254519715870e-05 * DAYS],
    m: [SOLAR_MASS, 9.54791938424326609e-04 * SOLAR_MASS, 2.85885980666130812e-04 * SOLAR_MASS, 4.36624404335156298e-05 * SOLAR_MASS, 5.15138902046611451e-05 * SOLAR_MASS],
  }
  let px = 0.0, py = 0.0, pz = 0.0
  for (let i = 0; i < 5; i++) {
    px += b.vx[i] * b.m[i]
    py += b.vy[i] * b.m[i]
    pz += b.vz[i] * b.m[i]
  }
  b.vx[0] = 0.0 - px / SOLAR_MASS
  b.vy[0] = 0.0 - py / SOLAR_MASS
  b.vz[0] = 0.0 - pz / SOLAR_MASS
  return b
}

function energy(b) {
  let e = 0.0
  for (let i = 0; i < 5; i++) {
    e += 0.5 * b.m[i] * (b.vx[i] * b.vx[i] + b.vy[i] * b.vy[i] + b.vz[i] * b.vz[i])
    for (let j = i + 1; j < 5; j++) {
      const dx = b.x[i] - b.x[j], dy = b.y[i] - b.y[j], dz = b.z[i] - b.z[j]
      e -= b.m[i] * b.m[j] / Math.sqrt(dx * dx + dy * dy + dz * dz)
    }
  }
  return e
}

function advance(b, dt) {
  for (let i = 0; i < 5; i++) {
    for (let j = i + 1; j < 5; j++) {
      const dx = b.x[i] - b.x[j], dy = b.y[i] - b.y[j], dz = b.z[i] - b.z[j]
      const d2 = dx * dx + dy * dy + dz * dz
      const mag = dt / (d2 * Math.sqrt(d2))
      const mi = b.m[i] * mag, mj = b.m[j] * mag
      b.vx[i] -= dx * mj
      b.vy[i] -= dy * mj
      b.vz[i] -= dz * mj
      b.vx[j] += dx * mi
      b.vy[j] += dy * mi
      b.vz[j] += dz * mi
    }
  }
  for (let i = 0; i < 5; i++) {
    b.x[i] += dt * b.vx[i]
    b.y[i] += dt * b.vy[i]
    b.z[i] += dt * b.vz[i]
  }
}

const b = bodies()
console.log(energy(b).toFixed(9))
for (let step = 0; step < 500000; step++) advance(b, 0.01)
console.log(energy(b).toFixed(9))
```

 Python

```tin
# N-body: the Jovian planets, a float-heavy simulation over arrays.
import math

SOLAR_MASS = 39.47841760435743  # 4 * pi * pi
DAYS = 365.24

def bodies():
    x = [0.0, 4.84143144246472090e+00, 8.34336671824457987e+00, 1.28943695621391310e+01, 1.53796971148509165e+01]
    y = [0.0, -1.16032004402742839e+00, 4.12479856412430479e+00, -1.51111514016986312e+01, -2.59193146099879641e+01]
    z = [0.0, -1.03622044471123109e-01, -4.03523417114321381e-01, -2.23307578892655734e-01, 1.79258772950371181e-01]
    vx = [0.0, 1.66007664274403694e-03 * DAYS, -2.76742510726862411e-03 * DAYS, 2.96460137564761618e-03 * DAYS, 2.68067772490389322e-03 * DAYS]
    vy = [0.0, 7.69901118419740425e-03 * DAYS, 4.99852801234917238e-03 * DAYS, 2.37847173959480950e-03 * DAYS, 1.62824170038242295e-03 * DAYS]
    vz = [0.0, -6.90460016972063023e-05 * DAYS, 2.30417297573763929e-05 * DAYS, -2.96589568540237556e-05 * DAYS, -9.51592254519715870e-05 * DAYS]
    m = [SOLAR_MASS, 9.54791938424326609e-04 * SOLAR_MASS, 2.85885980666130812e-04 * SOLAR_MASS, 4.36624404335156298e-05 * SOLAR_MASS, 5.15138902046611451e-05 * SOLAR_MASS]
    px = py = pz = 0.0
    for i in range(5):
        px += vx[i] * m[i]
        py += vy[i] * m[i]
        pz += vz[i] * m[i]
    vx[0] = 0.0 - px / SOLAR_MASS
    vy[0] = 0.0 - py / SOLAR_MASS
    vz[0] = 0.0 - pz / SOLAR_MASS
    return x, y, z, vx, vy, vz, m

def energy(b):
    x, y, z, vx, vy, vz, m = b
    e = 0.0
    for i in range(5):
        e += 0.5 * m[i] * (vx[i] * vx[i] + vy[i] * vy[i] + vz[i] * vz[i])
        for j in range(i + 1, 5):
            dx = x[i] - x[j]
            dy = y[i] - y[j]
            dz = z[i] - z[j]
            e -= m[i] * m[j] / math.sqrt(dx * dx + dy * dy + dz * dz)
    return e

def advance(b, dt):
    x, y, z, vx, vy, vz, m = b
    for i in range(5):
        for j in range(i + 1, 5):
            dx = x[i] - x[j]
            dy = y[i] - y[j]
            dz = z[i] - z[j]
            d2 = dx * dx + dy * dy + dz * dz
            mag = dt / (d2 * math.sqrt(d2))
            mi = m[i] * mag
            mj = m[j] * mag
            vx[i] -= dx * mj
            vy[i] -= dy * mj
            vz[i] -= dz * mj
            vx[j] += dx * mi
            vy[j] += dy * mi
            vz[j] += dz * mi
    for i in range(5):
        x[i] += dt * vx[i]
        y[i] += dt * vy[i]
        z[i] += dt * vz[i]

b = bodies()
print(f"{energy(b):.9f}")
for step in range(500000):
    advance(b, 0.01)
print(f"{energy(b):.9f}")
```

Tin

```tin
// Sieve of Eratosthenes: array writes in a tight loop.
fn main() {
  let limit = 10000000
  var composite = filled(limit, false)
  var count = 0
  var largest = 0
  for n in 2..limit {
    if composite[n] { continue }
    count += 1
    largest = n
    if n > limit / n { continue }
    var m = n * n
    while m < limit {
      composite[m] = true
      m += n
    }
  }
  print("{count} primes below {limit}, largest {largest}")
}
```

 JavaScript

```tin
// Sieve of Eratosthenes: array writes in a tight loop.
const limit = 10000000
const composite = new Array(limit).fill(false)
let count = 0
let largest = 0
for (let n = 2; n < limit; n++) {
  if (composite[n]) continue
  count++
  largest = n
  for (let m = n * n; m < limit; m += n) composite[m] = true
}
console.log(`${count} primes below ${limit}, largest ${largest}`)
```

 Python

```tin
# Sieve of Eratosthenes: array writes in a tight loop.
limit = 10000000
composite = [False] * limit
count = 0
largest = 0
for n in range(2, limit):
    if composite[n]:
        continue
    count += 1
    largest = n
    m = n * n
    while m < limit:
        composite[m] = True
        m += n
print(f"{count} primes below {limit}, largest {largest}")
```

## Method

MachineApple M5 Pro, 15 cores, 24 GB, macOS 27.2 arm64. Measured 2026-11-15 22:21 UTC. VersionsTin 0.1.0 (b9a1376) · Node v26.13.0 · Python 3.15.2 · rustc 1.100.0 (0ef1bc386 2026-11-09) · wasmtime 50.0.1 · Apple clang version 21.0.0 (clang-2100.4.1.1) Runs7 timed runs after 1 warm-up per program and language; interleaved: run i of every language, then run i + 1 of every language. Noisea program whose runs spread more than 15% (max / min) in any language is measured again, up to 2 times; if still noisy it is marked noisy. Load average 4.18 at the start, 2.58 at the end. Largest spread in any cell: 14%. No program is marked noisy. Timingwall time of the whole process (startup included), measured by the harness around each spawn; inProcess: the same run timed inside the process by bench/tin-run.mjs, js-run.mjs, py-run.py (load + compile + run, no interpreter startup) Memorypeak RSS from /usr/bin/time -l, max over runs Tincompiled once with `tin build`; timed runs execute the .wasm with bench/tin-run.mjs on Node Rustrustc -C opt-level=3, standard library only Tin WASItin build --target wasi, run by `wasmtime run` (wall time includes Cranelift compiling the module); not for programs with agents Tin nativetin build --native: wasm2c + cc -O2, one executable; not for programs with agents PythonCPython, no third-party packages. CPython 3.11+ is noticeably faster at loops and calls than 3.9. JavaScriptNode, plain .js Rerun it`npm install && npm run bench` (Node ≥ 24, python3, rustc). One machine, other programs open: treat differences under ~10% as noise.

## The programs

**hello — hello

Every version prints `hello`

Tin · main.tin

```tin
fn main() {
  print("hello")
}
```

JavaScript · main.js

```tin
console.log('hello')
```

Python · main.py

```tin
print("hello")
```

Rust · main.rs

```tin
fn main() {
    println!("hello");
}
```

**agent — Agent-loop overhead: N prompts, each one model call -> one tool call -> one model call.

Every version prints `50000 agent runs, 50000 tool calls, checksum 1250025000`

Tin · main.tin

```tin
// Agent-loop overhead: N prompts, each one model call -> one tool call -> one model call.
// The model is the built-in offline "mock", so this measures the loop, not a network.

/// Add two integers.
tool fn add(a: int, b: int): int => a + b

agent Calc {
  model: "mock"
  system: "You are a calculator. Use the tools."
  tools: [add]
}

fn main() {
  let n = 50000
  var total = 0
  for i in 0..n {
    let reply = Calc("add {i} and 1")
    Calc.reset()
    total += parseInt(reply.slice(6, reply.len)).or(0)
  }
  print("{n} agent runs, {n} tool calls, checksum {total}")
}
```

JavaScript · main.js

```tin
// Agent-loop overhead: N prompts, each one model call -> one tool call -> one model call.
// A hand-written loop with the same steps as Tin's runtime and its offline "mock" model:
// the model reads numbers from the prompt, asks for a tool by name with JSON input,
// the loop runs the tool and sends the result back, the model answers with text.

const TOOLS = {
  add: {
    fn: ({ a, b }) => a + b,
    schema: { type: 'object', properties: { a: { type: 'integer' }, b: { type: 'integer' } }, required: ['a', 'b'] },
  },
}

async function mockModel(messages, tools) {
  const last = messages[messages.length - 1].content
  const results = last.filter((b) => b.type === 'tool_result')
  if (results.length) return { content: [{ type: 'text', text: 'mock: ' + results.map((r) => r.text).join('; ') }], stop: 'end' }
  const prompt = last.filter((b) => b.type === 'text').map((b) => b.text).join('\n')
  const names = Object.keys(tools)
  const named = names.filter((n) => prompt.toLowerCase().includes(n))
  const nums = (prompt.match(/-?\d+(\.\d+)?/g) ?? []).map(Number)
  const calls = (named.length ? named : names.slice(0, 1)).map((name, i) => ({
    type: 'tool_use',
    id: `mock_${i}`,
    name,
    input: Object.fromEntries(tools[name].schema.required.map((k) => [k, Math.round(nums.shift() ?? 0)])),
  }))
  return { content: calls, stop: 'tool_use' }
}

async function runAgent(history, prompt, maxTurns = 20) {
  history.push({ role: 'user', content: [{ type: 'text', text: prompt }] })
  for (let turn = 0; turn < maxTurns; turn++) {
    const reply = await mockModel(history, TOOLS)
    history.push({ role: 'assistant', content: reply.content })
    if (reply.stop !== 'tool_use') return reply.content.filter((b) => b.type === 'text').map((b) => b.text).join('')
    const results = []
    for (const call of reply.content) {
      const args = JSON.parse(JSON.stringify(call.input)) // the wire format
      const out = await TOOLS[call.name].fn(args)
      results.push({ type: 'tool_result', id: call.id, text: JSON.stringify(out) })
    }
    history.push({ role: 'user', content: results })
  }
  throw new Error('did not finish')
}

const n = 50000
let total = 0
for (let i = 0; i < n; i++) {
  const reply = await runAgent([], `add ${i} and 1`)
  total += parseInt(reply.slice(6))
}
console.log(`${n} agent runs, ${n} tool calls, checksum ${total}`)
```

Python · main.py

```tin
# Agent-loop overhead: N prompts, each one model call -> one tool call -> one model call.
# A hand-written loop with the same steps as Tin's runtime and its offline "mock" model:
# the model reads numbers from the prompt, asks for a tool by name with JSON input,
# the loop runs the tool and sends the result back, the model answers with text.
import json
import re

TOOLS = {
    "add": {
        "fn": lambda a, b: a + b,
        "schema": {"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"]},
    }
}
NUM = re.compile(r"-?\d+(\.\d+)?")

def mock_model(messages, tools):
    last = messages[-1]["content"]
    results = [b for b in last if b["type"] == "tool_result"]
    if results:
        return {"content": [{"type": "text", "text": "mock: " + "; ".join(r["text"] for r in results)}], "stop": "end"}
    prompt = "\n".join(b["text"] for b in last if b["type"] == "text")
    named = [name for name in tools if name in prompt.lower()] or list(tools)[:1]
    nums = [float(m.group(0)) for m in NUM.finditer(prompt)]
    calls = []
    for i, name in enumerate(named):
        schema = tools[name]["schema"]
        args = {k: round(nums.pop(0)) if nums else 0 for k in schema["required"]}
        calls.append({"type": "tool_use", "id": f"mock_{i}", "name": name, "input": args})
    return {"content": calls, "stop": "tool_use"}

def run_agent(history, prompt, max_turns=20):
    history.append({"role": "user", "content": [{"type": "text", "text": prompt}]})
    for _ in range(max_turns):
        reply = mock_model(history, TOOLS)
        history.append({"role": "assistant", "content": reply["content"]})
        if reply["stop"] != "tool_use":
            return "".join(b["text"] for b in reply["content"] if b["type"] == "text")
        results = []
        for call in reply["content"]:
            args = json.loads(json.dumps(call["input"]))  # the wire format
            out = TOOLS[call["name"]]["fn"](**args)
            results.append({"type": "tool_result", "id": call["id"], "text": json.dumps(out)})
        history.append({"role": "user", "content": results})
    raise RuntimeError("did not finish")

n = 50000
total = 0
for i in range(n):
    history = []
    reply = run_agent(history, f"add {i} and 1")
    total += int(reply[6:])
print(f"{n} agent runs, {n} tool calls, checksum {total}")
```

Rust · main.rs

```tin
// Agent-loop overhead: N prompts, each one model call -> one tool call -> one model call.
// A hand-written loop with the same steps as Tin's runtime and its offline "mock" model:
// the model reads numbers from the prompt, asks for a tool by name with JSON input,
// the loop runs the tool and sends the result back, the model answers with text.
// Standard library only, so the JSON wire format is written and read by hand.

enum Block {
    Text(String),
    ToolUse { id: String, name: String, input: String },
    ToolResult { #[allow(dead_code)] id: String, text: String },
}

struct Message { content: Vec<Block> }

struct Tool { name: &'static str, params: &'static [&'static str], run: fn(&[i64]) -> i64 }

const TOOLS: &[Tool] = &[Tool { name: "add", params: &["a", "b"], run: |x| x[0] + x[1] }];

fn numbers(text: &str) -> Vec<f64> {
    let (mut out, bytes) = (Vec::new(), text.as_bytes());
    let mut i = 0;
    while i < bytes.len() {
        let start = i;
        if bytes[i] == b'-' && i + 1 < bytes.len() && bytes[i + 1].is_ascii_digit() { i += 1; }
        if i < bytes.len() && bytes[i].is_ascii_digit() {
            while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'.') { i += 1; }
            out.push(text[start..i].parse().unwrap());
        } else {
            i = start + 1;
        }
    }
    out
}

fn mock_model(messages: &[Message]) -> (Vec<Block>, bool) {
    let last = &messages[messages.len() - 1].content;
    let results: Vec<&str> = last.iter().filter_map(|b| if let Block::ToolResult { text, .. } = b { Some(text.as_str()) } else { None }).collect();
    if !results.is_empty() {
        return (vec![Block::Text(format!("mock: {}", results.join("; ")))], false);
    }
    let prompt: Vec<&str> = last.iter().filter_map(|b| if let Block::Text(t) = b { Some(t.as_str()) } else { None }).collect();
    let prompt = prompt.join("\n");
    let lower = prompt.to_lowercase();
    let mut named: Vec<&Tool> = TOOLS.iter().filter(|t| lower.contains(t.name)).collect();
    if named.is_empty() { named.push(&TOOLS[0]); }
    let mut nums = numbers(&prompt).into_iter();
    let calls = named.iter().enumerate().map(|(i, t)| {
        let fields: Vec<String> = t.params.iter().map(|p| format!("\"{}\":{}", p, nums.next().unwrap_or(0.0).round() as i64)).collect();
        Block::ToolUse { id: format!("mock_{}", i), name: t.name.to_string(), input: format!("{{{}}}", fields.join(",")) }
    }).collect();
    (calls, true)
}

/// Reads the integer fields of a flat JSON object, in the tool's parameter order.
fn parse_args(json: &str, params: &[&str]) -> Vec<i64> {
    params.iter().map(|p| {
        let key = format!("\"{}\":", p);
        let at = json.find(&key).unwrap() + key.len();
        let end = json[at..].find(|c| c == ',' || c == '}').unwrap() + at;
        json[at..end].parse().unwrap()
    }).collect()
}

fn run_agent(history: &mut Vec<Message>, prompt: String) -> String {
    history.push(Message { content: vec![Block::Text(prompt)] });
    for _ in 0..20 {
        let (content, wants_tools) = mock_model(history);
        if !wants_tools {
            return content.iter().filter_map(|b| if let Block::Text(t) = b { Some(t.as_str()) } else { None }).collect();
        }
        let mut results = Vec::new();
        for b in &content {
            if let Block::ToolUse { id, name, input } = b {
                let tool = TOOLS.iter().find(|t| t.name == name).unwrap();
                let out = (tool.run)(&parse_args(input, tool.params));
                results.push(Block::ToolResult { id: id.clone(), text: out.to_string() });
            }
        }
        history.push(Message { content });
        history.push(Message { content: results });
    }
    panic!("did not finish")
}

fn main() {
    let n = std::hint::black_box(50000);
    let mut total: i64 = 0;
    for i in 0..n {
        let mut history = Vec::new();
        let reply = run_agent(&mut history, format!("add {} and 1", i));
        total += reply[6..].parse::<i64>().unwrap();
    }
    println!("{} agent runs, {} tool calls, checksum {}", n, n, total);
}
```

**fib — Recursive Fibonacci: function-call overhead.

Every version prints `fib(36) = 14930352`

Tin · main.tin

```tin
// Recursive Fibonacci: function-call overhead.
fn fib(n: int): int => if n < 2 { n } else { fib(n - 1) + fib(n - 2) }

fn main() {
  print("fib(36) = {fib(36)}")
}
```

JavaScript · main.js

```tin
// Recursive Fibonacci: function-call overhead.
function fib(n) {
  return n < 2 ? n : fib(n - 1) + fib(n - 2)
}

console.log(`fib(36) = ${fib(36)}`)
```

Python · main.py

```tin
# Recursive Fibonacci: function-call overhead.
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(f"fib(36) = {fib(36)}")
```

Rust · main.rs

```tin
// Recursive Fibonacci: function-call overhead.
fn fib(n: i32) -> i32 {
    if n < 2 { n } else { fib(n - 1) + fib(n - 2) }
}

fn main() {
    println!("fib(36) = {}", fib(std::hint::black_box(36)));
}
```

**mandelbrot — Mandelbrot set: floating-point arithmetic in nested loops.

Every version prints `800x800: 108635 points inside, 24366700 iterations`

Tin · main.tin

```tin
// Mandelbrot set: floating-point arithmetic in nested loops.
fn escape(cr: float, ci: float, limit: int): int {
  var zr = 0.0
  var zi = 0.0
  var i = 0
  while i < limit && zr * zr + zi * zi <= 4.0 {
    let next = zr * zr - zi * zi + cr
    zi = 2.0 * zr * zi + ci
    zr = next
    i += 1
  }
  i
}

fn main() {
  let size = 800
  var total = 0
  var inside = 0
  for row in 0..size {
    for col in 0..size {
      let x = float(col) / float(size) * 3.0 - 2.0
      let y = float(row) / float(size) * 3.0 - 1.5
      let n = escape(x, y, 200)
      total += n
      if n == 200 { inside += 1 }
    }
  }
  print("{size}x{size}: {inside} points inside, {total} iterations")
}
```

JavaScript · main.js

```tin
// Mandelbrot set: floating-point arithmetic in nested loops.
function escape(cr, ci, limit) {
  let zr = 0.0, zi = 0.0, i = 0
  while (i < limit && zr * zr + zi * zi <= 4.0) {
    const next = zr * zr - zi * zi + cr
    zi = 2.0 * zr * zi + ci
    zr = next
    i++
  }
  return i
}

const size = 800
let total = 0, inside = 0
for (let row = 0; row < size; row++) {
  for (let col = 0; col < size; col++) {
    const x = col / size * 3.0 - 2.0
    const y = row / size * 3.0 - 1.5
    const n = escape(x, y, 200)
    total += n
    if (n === 200) inside++
  }
}
console.log(`${size}x${size}: ${inside} points inside, ${total} iterations`)
```

Python · main.py

```tin
# Mandelbrot set: floating-point arithmetic in nested loops.
def escape(cr, ci, limit):
    zr = 0.0
    zi = 0.0
    i = 0
    while i < limit and zr * zr + zi * zi <= 4.0:
        nxt = zr * zr - zi * zi + cr
        zi = 2.0 * zr * zi + ci
        zr = nxt
        i += 1
    return i

size = 800
total = 0
inside = 0
for row in range(size):
    for col in range(size):
        x = col / size * 3.0 - 2.0
        y = row / size * 3.0 - 1.5
        n = escape(x, y, 200)
        total += n
        if n == 200:
            inside += 1
print(f"{size}x{size}: {inside} points inside, {total} iterations")
```

Rust · main.rs

```tin
// Mandelbrot set: floating-point arithmetic in nested loops.
fn escape(cr: f64, ci: f64, limit: i32) -> i32 {
    let (mut zr, mut zi, mut i) = (0.0f64, 0.0f64, 0);
    while i < limit && zr * zr + zi * zi <= 4.0 {
        let next = zr * zr - zi * zi + cr;
        zi = 2.0 * zr * zi + ci;
        zr = next;
        i += 1;
    }
    i
}

fn main() {
    let size: i32 = std::hint::black_box(800);
    let (mut total, mut inside) = (0i32, 0i32);
    for row in 0..size {
        for col in 0..size {
            let x = col as f64 / size as f64 * 3.0 - 2.0;
            let y = row as f64 / size as f64 * 3.0 - 1.5;
            let n = escape(x, y, 200);
            total += n;
            if n == 200 { inside += 1; }
        }
    }
    println!("{}x{}: {} points inside, {} iterations", size, size, inside, total);
}
```

**nbody — N-body: the Jovian planets, a float-heavy simulation over arrays.

Every version prints `-0.169075164`

Tin · main.tin

```tin
// N-body: the Jovian planets, a float-heavy simulation over arrays.
let SOLAR_MASS = 39.47841760435743  // 4 * pi * pi
let DAYS = 365.24

type Bodies = { x: float[], y: float[], z: float[], vx: float[], vy: float[], vz: float[], m: float[] }

fn bodies(): Bodies {
  var b = Bodies {
    x: [0.0, 4.84143144246472090e+00, 8.34336671824457987e+00, 1.28943695621391310e+01, 1.53796971148509165e+01],
    y: [0.0, -1.16032004402742839e+00, 4.12479856412430479e+00, -1.51111514016986312e+01, -2.59193146099879641e+01],
    z: [0.0, -1.03622044471123109e-01, -4.03523417114321381e-01, -2.23307578892655734e-01, 1.79258772950371181e-01],
    vx: [0.0, 1.66007664274403694e-03 * DAYS, -2.76742510726862411e-03 * DAYS, 2.96460137564761618e-03 * DAYS, 2.68067772490389322e-03 * DAYS],
    vy: [0.0, 7.69901118419740425e-03 * DAYS, 4.99852801234917238e-03 * DAYS, 2.37847173959480950e-03 * DAYS, 1.62824170038242295e-03 * DAYS],
    vz: [0.0, -6.90460016972063023e-05 * DAYS, 2.30417297573763929e-05 * DAYS, -2.96589568540237556e-05 * DAYS, -9.51592254519715870e-05 * DAYS],
    m: [SOLAR_MASS, 9.54791938424326609e-04 * SOLAR_MASS, 2.85885980666130812e-04 * SOLAR_MASS, 4.36624404335156298e-05 * SOLAR_MASS, 5.15138902046611451e-05 * SOLAR_MASS],
  }
  // offset the sun's momentum so the system's total is zero
  var px = 0.0
  var py = 0.0
  var pz = 0.0
  for i in 0..5 {
    px += b.vx[i] * b.m[i]
    py += b.vy[i] * b.m[i]
    pz += b.vz[i] * b.m[i]
  }
  b.vx[0] = 0.0 - px / SOLAR_MASS
  b.vy[0] = 0.0 - py / SOLAR_MASS
  b.vz[0] = 0.0 - pz / SOLAR_MASS
  b
}

fn energy(b: Bodies): float {
  var e = 0.0
  for i in 0..5 {
    e += 0.5 * b.m[i] * (b.vx[i] * b.vx[i] + b.vy[i] * b.vy[i] + b.vz[i] * b.vz[i])
    for j in i + 1..5 {
      let dx = b.x[i] - b.x[j]
      let dy = b.y[i] - b.y[j]
      let dz = b.z[i] - b.z[j]
      e -= b.m[i] * b.m[j] / sqrt(dx * dx + dy * dy + dz * dz)
    }
  }
  e
}

fn advance(b: inout Bodies, dt: float) {
  for i in 0..5 {
    for j in i + 1..5 {
      let dx = b.x[i] - b.x[j]
      let dy = b.y[i] - b.y[j]
      let dz = b.z[i] - b.z[j]
      let d2 = dx * dx + dy * dy + dz * dz
      let mag = dt / (d2 * sqrt(d2))
      let mi = b.m[i] * mag
      let mj = b.m[j] * mag
      b.vx[i] -= dx * mj
      b.vy[i] -= dy * mj
      b.vz[i] -= dz * mj
      b.vx[j] += dx * mi
      b.vy[j] += dy * mi
      b.vz[j] += dz * mi
    }
  }
  for i in 0..5 {
    b.x[i] += dt * b.vx[i]
    b.y[i] += dt * b.vy[i]
    b.z[i] += dt * b.vz[i]
  }
}

fn main() {
  var b = bodies()
  print(energy(b).fixed(9))
  for step in 0..500000 { advance(&b, 0.01) }
  print(energy(b).fixed(9))
}
```

JavaScript · main.js

```tin
// N-body: the Jovian planets, a float-heavy simulation over arrays.
const SOLAR_MASS = 39.47841760435743 // 4 * pi * pi
const DAYS = 365.24

function bodies() {
  const b = {
    x: [0.0, 4.84143144246472090e+00, 8.34336671824457987e+00, 1.28943695621391310e+01, 1.53796971148509165e+01],
    y: [0.0, -1.16032004402742839e+00, 4.12479856412430479e+00, -1.51111514016986312e+01, -2.59193146099879641e+01],
    z: [0.0, -1.03622044471123109e-01, -4.03523417114321381e-01, -2.23307578892655734e-01, 1.79258772950371181e-01],
    vx: [0.0, 1.66007664274403694e-03 * DAYS, -2.76742510726862411e-03 * DAYS, 2.96460137564761618e-03 * DAYS, 2.68067772490389322e-03 * DAYS],
    vy: [0.0, 7.69901118419740425e-03 * DAYS, 4.99852801234917238e-03 * DAYS, 2.37847173959480950e-03 * DAYS, 1.62824170038242295e-03 * DAYS],
    vz: [0.0, -6.90460016972063023e-05 * DAYS, 2.30417297573763929e-05 * DAYS, -2.96589568540237556e-05 * DAYS, -9.51592254519715870e-05 * DAYS],
    m: [SOLAR_MASS, 9.54791938424326609e-04 * SOLAR_MASS, 2.85885980666130812e-04 * SOLAR_MASS, 4.36624404335156298e-05 * SOLAR_MASS, 5.15138902046611451e-05 * SOLAR_MASS],
  }
  let px = 0.0, py = 0.0, pz = 0.0
  for (let i = 0; i < 5; i++) {
    px += b.vx[i] * b.m[i]
    py += b.vy[i] * b.m[i]
    pz += b.vz[i] * b.m[i]
  }
  b.vx[0] = 0.0 - px / SOLAR_MASS
  b.vy[0] = 0.0 - py / SOLAR_MASS
  b.vz[0] = 0.0 - pz / SOLAR_MASS
  return b
}

function energy(b) {
  let e = 0.0
  for (let i = 0; i < 5; i++) {
    e += 0.5 * b.m[i] * (b.vx[i] * b.vx[i] + b.vy[i] * b.vy[i] + b.vz[i] * b.vz[i])
    for (let j = i + 1; j < 5; j++) {
      const dx = b.x[i] - b.x[j], dy = b.y[i] - b.y[j], dz = b.z[i] - b.z[j]
      e -= b.m[i] * b.m[j] / Math.sqrt(dx * dx + dy * dy + dz * dz)
    }
  }
  return e
}

function advance(b, dt) {
  for (let i = 0; i < 5; i++) {
    for (let j = i + 1; j < 5; j++) {
      const dx = b.x[i] - b.x[j], dy = b.y[i] - b.y[j], dz = b.z[i] - b.z[j]
      const d2 = dx * dx + dy * dy + dz * dz
      const mag = dt / (d2 * Math.sqrt(d2))
      const mi = b.m[i] * mag, mj = b.m[j] * mag
      b.vx[i] -= dx * mj
      b.vy[i] -= dy * mj
      b.vz[i] -= dz * mj
      b.vx[j] += dx * mi
      b.vy[j] += dy * mi
      b.vz[j] += dz * mi
    }
  }
  for (let i = 0; i < 5; i++) {
    b.x[i] += dt * b.vx[i]
    b.y[i] += dt * b.vy[i]
    b.z[i] += dt * b.vz[i]
  }
}

const b = bodies()
console.log(energy(b).toFixed(9))
for (let step = 0; step < 500000; step++) advance(b, 0.01)
console.log(energy(b).toFixed(9))
```

Python · main.py

```tin
# N-body: the Jovian planets, a float-heavy simulation over arrays.
import math

SOLAR_MASS = 39.47841760435743  # 4 * pi * pi
DAYS = 365.24

def bodies():
    x = [0.0, 4.84143144246472090e+00, 8.34336671824457987e+00, 1.28943695621391310e+01, 1.53796971148509165e+01]
    y = [0.0, -1.16032004402742839e+00, 4.12479856412430479e+00, -1.51111514016986312e+01, -2.59193146099879641e+01]
    z = [0.0, -1.03622044471123109e-01, -4.03523417114321381e-01, -2.23307578892655734e-01, 1.79258772950371181e-01]
    vx = [0.0, 1.66007664274403694e-03 * DAYS, -2.76742510726862411e-03 * DAYS, 2.96460137564761618e-03 * DAYS, 2.68067772490389322e-03 * DAYS]
    vy = [0.0, 7.69901118419740425e-03 * DAYS, 4.99852801234917238e-03 * DAYS, 2.37847173959480950e-03 * DAYS, 1.62824170038242295e-03 * DAYS]
    vz = [0.0, -6.90460016972063023e-05 * DAYS, 2.30417297573763929e-05 * DAYS, -2.96589568540237556e-05 * DAYS, -9.51592254519715870e-05 * DAYS]
    m = [SOLAR_MASS, 9.54791938424326609e-04 * SOLAR_MASS, 2.85885980666130812e-04 * SOLAR_MASS, 4.36624404335156298e-05 * SOLAR_MASS, 5.15138902046611451e-05 * SOLAR_MASS]
    px = py = pz = 0.0
    for i in range(5):
        px += vx[i] * m[i]
        py += vy[i] * m[i]
        pz += vz[i] * m[i]
    vx[0] = 0.0 - px / SOLAR_MASS
    vy[0] = 0.0 - py / SOLAR_MASS
    vz[0] = 0.0 - pz / SOLAR_MASS
    return x, y, z, vx, vy, vz, m

def energy(b):
    x, y, z, vx, vy, vz, m = b
    e = 0.0
    for i in range(5):
        e += 0.5 * m[i] * (vx[i] * vx[i] + vy[i] * vy[i] + vz[i] * vz[i])
        for j in range(i + 1, 5):
            dx = x[i] - x[j]
            dy = y[i] - y[j]
            dz = z[i] - z[j]
            e -= m[i] * m[j] / math.sqrt(dx * dx + dy * dy + dz * dz)
    return e

def advance(b, dt):
    x, y, z, vx, vy, vz, m = b
    for i in range(5):
        for j in range(i + 1, 5):
            dx = x[i] - x[j]
            dy = y[i] - y[j]
            dz = z[i] - z[j]
            d2 = dx * dx + dy * dy + dz * dz
            mag = dt / (d2 * math.sqrt(d2))
            mi = m[i] * mag
            mj = m[j] * mag
            vx[i] -= dx * mj
            vy[i] -= dy * mj
            vz[i] -= dz * mj
            vx[j] += dx * mi
            vy[j] += dy * mi
            vz[j] += dz * mi
    for i in range(5):
        x[i] += dt * vx[i]
        y[i] += dt * vy[i]
        z[i] += dt * vz[i]

b = bodies()
print(f"{energy(b):.9f}")
for step in range(500000):
    advance(b, 0.01)
print(f"{energy(b):.9f}")
```

Rust · main.rs

```tin
// N-body: the Jovian planets, a float-heavy simulation over arrays.
const SOLAR_MASS: f64 = 39.47841760435743; // 4 * pi * pi
const DAYS: f64 = 365.24;

struct Bodies { x: Vec<f64>, y: Vec<f64>, z: Vec<f64>, vx: Vec<f64>, vy: Vec<f64>, vz: Vec<f64>, m: Vec<f64> }

fn bodies() -> Bodies {
    let mut b = Bodies {
        x: vec![0.0, 4.84143144246472090e+00, 8.34336671824457987e+00, 1.28943695621391310e+01, 1.53796971148509165e+01],
        y: vec![0.0, -1.16032004402742839e+00, 4.12479856412430479e+00, -1.51111514016986312e+01, -2.59193146099879641e+01],
        z: vec![0.0, -1.03622044471123109e-01, -4.03523417114321381e-01, -2.23307578892655734e-01, 1.79258772950371181e-01],
        vx: vec![0.0, 1.66007664274403694e-03 * DAYS, -2.76742510726862411e-03 * DAYS, 2.96460137564761618e-03 * DAYS, 2.68067772490389322e-03 * DAYS],
        vy: vec![0.0, 7.69901118419740425e-03 * DAYS, 4.99852801234917238e-03 * DAYS, 2.37847173959480950e-03 * DAYS, 1.62824170038242295e-03 * DAYS],
        vz: vec![0.0, -6.90460016972063023e-05 * DAYS, 2.30417297573763929e-05 * DAYS, -2.96589568540237556e-05 * DAYS, -9.51592254519715870e-05 * DAYS],
        m: vec![SOLAR_MASS, 9.54791938424326609e-04 * SOLAR_MASS, 2.85885980666130812e-04 * SOLAR_MASS, 4.36624404335156298e-05 * SOLAR_MASS, 5.15138902046611451e-05 * SOLAR_MASS],
    };
    let (mut px, mut py, mut pz) = (0.0, 0.0, 0.0);
    for i in 0..5 {
        px += b.vx[i] * b.m[i];
        py += b.vy[i] * b.m[i];
        pz += b.vz[i] * b.m[i];
    }
    b.vx[0] = 0.0 - px / SOLAR_MASS;
    b.vy[0] = 0.0 - py / SOLAR_MASS;
    b.vz[0] = 0.0 - pz / SOLAR_MASS;
    b
}

fn energy(b: &Bodies) -> f64 {
    let mut e = 0.0;
    for i in 0..5 {
        e += 0.5 * b.m[i] * (b.vx[i] * b.vx[i] + b.vy[i] * b.vy[i] + b.vz[i] * b.vz[i]);
        for j in i + 1..5 {
            let (dx, dy, dz) = (b.x[i] - b.x[j], b.y[i] - b.y[j], b.z[i] - b.z[j]);
            e -= b.m[i] * b.m[j] / (dx * dx + dy * dy + dz * dz).sqrt();
        }
    }
    e
}

fn advance(b: &mut Bodies, dt: f64) {
    for i in 0..5 {
        for j in i + 1..5 {
            let (dx, dy, dz) = (b.x[i] - b.x[j], b.y[i] - b.y[j], b.z[i] - b.z[j]);
            let d2 = dx * dx + dy * dy + dz * dz;
            let mag = dt / (d2 * d2.sqrt());
            let (mi, mj) = (b.m[i] * mag, b.m[j] * mag);
            b.vx[i] -= dx * mj;
            b.vy[i] -= dy * mj;
            b.vz[i] -= dz * mj;
            b.vx[j] += dx * mi;
            b.vy[j] += dy * mi;
            b.vz[j] += dz * mi;
        }
    }
    for i in 0..5 {
        b.x[i] += dt * b.vx[i];
        b.y[i] += dt * b.vy[i];
        b.z[i] += dt * b.vz[i];
    }
}

fn main() {
    let mut b = bodies();
    println!("{:.9}", energy(&b));
    let steps = std::hint::black_box(500000);
    for _ in 0..steps { advance(&mut b, 0.01); }
    println!("{:.9}", energy(&b));
}
```

**sieve — Sieve of Eratosthenes: array writes in a tight loop.

Every version prints `664579 primes below 10000000, largest 9999991`

Tin · main.tin

```tin
// Sieve of Eratosthenes: array writes in a tight loop.
fn main() {
  let limit = 10000000
  var composite = filled(limit, false)
  var count = 0
  var largest = 0
  for n in 2..limit {
    if composite[n] { continue }
    count += 1
    largest = n
    if n > limit / n { continue }
    var m = n * n
    while m < limit {
      composite[m] = true
      m += n
    }
  }
  print("{count} primes below {limit}, largest {largest}")
}
```

JavaScript · main.js

```tin
// Sieve of Eratosthenes: array writes in a tight loop.
const limit = 10000000
const composite = new Array(limit).fill(false)
let count = 0
let largest = 0
for (let n = 2; n < limit; n++) {
  if (composite[n]) continue
  count++
  largest = n
  for (let m = n * n; m < limit; m += n) composite[m] = true
}
console.log(`${count} primes below ${limit}, largest ${largest}`)
```

Python · main.py

```tin
# Sieve of Eratosthenes: array writes in a tight loop.
limit = 10000000
composite = [False] * limit
count = 0
largest = 0
for n in range(2, limit):
    if composite[n]:
        continue
    count += 1
    largest = n
    m = n * n
    while m < limit:
        composite[m] = True
        m += n
print(f"{count} primes below {limit}, largest {largest}")
```

Rust · main.rs

```tin
// Sieve of Eratosthenes: array writes in a tight loop.
fn main() {
    let limit: usize = std::hint::black_box(10_000_000);
    let mut composite = vec![false; limit];
    let mut count = 0;
    let mut largest = 0;
    for n in 2..limit {
        if composite[n] { continue; }
        count += 1;
        largest = n;
        let mut m = n * n;
        while m < limit {
            composite[m] = true;
            m += n;
        }
    }
    println!("{} primes below {}, largest {}", count, limit, largest);
}
```

**sort — Sorting a million random integers.

Every version prints `2000000 sorted: first 1156, median 1073683925, last 2147482835, check 999660`

Tin · main.tin

```tin
// Sorting a million random integers.

/// Park-Miller "minimal standard" random numbers (Schrage's method: never overflows 32 bits).
fn nextRand(s: int): int {
  let t = 16807 * (s % 127773) - 2836 * (s / 127773)
  if t <= 0 { t + 2147483647 } else { t }
}

fn main() {
  var seed = 7
  var xs: int[] = []
  for i in 0..2000000 {
    seed = nextRand(seed)
    xs.push(seed)
  }
  let s = sort(xs)
  for i in 1..s.len {
    if s[i - 1] > s[i] { panic("not sorted at {i}") }
  }
  var check = 0
  var i = 0
  while i < s.len {
    check = (check + s[i] % 1000) % 1000000
    i += 1000
  }
  print("{s.len} sorted: first {s[0]}, median {s[s.len / 2]}, last {s[s.len - 1]}, check {check}")
}
```

JavaScript · main.js

```tin
// Sorting a million random integers.

/** Park-Miller "minimal standard" random numbers (Schrage's method: never overflows 32 bits). */
function nextRand(s) {
  const t = 16807 * (s % 127773) - 2836 * Math.floor(s / 127773)
  return t <= 0 ? t + 2147483647 : t
}

let seed = 7
const xs = []
for (let i = 0; i < 2000000; i++) {
  seed = nextRand(seed)
  xs.push(seed)
}
const s = [...xs].sort((a, b) => a - b)
for (let i = 1; i < s.length; i++) {
  if (s[i - 1] > s[i]) throw new Error(`not sorted at ${i}`)
}
let check = 0
for (let i = 0; i < s.length; i += 1000) check = (check + s[i] % 1000) % 1000000
console.log(`${s.length} sorted: first ${s[0]}, median ${s[Math.floor(s.length / 2)]}, last ${s[s.length - 1]}, check ${check}`)
```

Python · main.py

```tin
# Sorting a million random integers.

def next_rand(s):
    """Park-Miller "minimal standard" random numbers (Schrage's method: never overflows 32 bits)."""
    t = 16807 * (s % 127773) - 2836 * (s // 127773)
    return t + 2147483647 if t <= 0 else t

seed = 7
xs = []
for i in range(2000000):
    seed = next_rand(seed)
    xs.append(seed)
s = sorted(xs)
for i in range(1, len(s)):
    if s[i - 1] > s[i]:
        raise SystemExit(f"not sorted at {i}")
check = 0
for i in range(0, len(s), 1000):
    check = (check + s[i] % 1000) % 1000000
print(f"{len(s)} sorted: first {s[0]}, median {s[len(s) // 2]}, last {s[-1]}, check {check}")
```

Rust · main.rs

```tin
// Sorting a million random integers.

/// Park-Miller "minimal standard" random numbers (Schrage's method: never overflows 32 bits).
fn next_rand(s: i32) -> i32 {
    let t = 16807 * (s % 127773) - 2836 * (s / 127773);
    if t <= 0 { t + 2147483647 } else { t }
}

fn main() {
    let mut seed = std::hint::black_box(7);
    let mut xs: Vec<i32> = Vec::new();
    for _ in 0..2000000 {
        seed = next_rand(seed);
        xs.push(seed);
    }
    let mut s = xs.clone();
    s.sort();
    for i in 1..s.len() {
        if s[i - 1] > s[i] { panic!("not sorted at {}", i); }
    }
    let mut check = 0;
    for i in (0..s.len()).step_by(1000) { check = (check + s[i] % 1000) % 1000000; }
    println!("{} sorted: first {}, median {}, last {}, check {}", s.len(), s[0], s[s.len() / 2], s[s.len() - 1], check);
}
```

**trees — Binary trees: allocate and free many small trees (the benchmarks-game shape).

Every version prints `stretch tree of depth 17 check: 262143`

Tin · main.tin

```tin
// Binary trees: allocate and free many small trees (the benchmarks-game shape).

type Tree =
  | Empty
  | Node { left: Tree, right: Tree }

fn make(depth: int): Tree =>
  if depth == 0 { Node { left: Empty, right: Empty } }
  else { Node { left: make(depth - 1), right: make(depth - 1) } }

fn check(t: Tree): int => match t {
  Empty => 0
  Node { left, right } => 1 + check(left) + check(right)
}

fn main() {
  let maxDepth = 16
  let stretch = maxDepth + 1
  print("stretch tree of depth {stretch} check: {check(make(stretch))}")
  let longLived = make(maxDepth)
  var depth = 4
  while depth <= maxDepth {
    let iterations = 1.shl(maxDepth - depth + 4)
    var total = 0
    for i in 0..iterations {
      total += check(make(depth))
    }
    print("{iterations} trees of depth {depth} check: {total}")
    depth += 2
  }
  print("long lived tree of depth {maxDepth} check: {check(longLived)}")
}
```

JavaScript · main.js

```tin
// Binary trees: allocate and free many small trees (the benchmarks-game shape).

function make(depth) {
  // null is the empty tree
  if (depth === 0) return { left: null, right: null }
  return { left: make(depth - 1), right: make(depth - 1) }
}

function check(t) {
  if (t === null) return 0
  return 1 + check(t.left) + check(t.right)
}

const maxDepth = 16
const stretch = maxDepth + 1
console.log(`stretch tree of depth ${stretch} check: ${check(make(stretch))}`)
const longLived = make(maxDepth)
for (let depth = 4; depth <= maxDepth; depth += 2) {
  const iterations = 1 << (maxDepth - depth + 4)
  let total = 0
  for (let i = 0; i < iterations; i++) total += check(make(depth))
  console.log(`${iterations} trees of depth ${depth} check: ${total}`)
}
console.log(`long lived tree of depth ${maxDepth} check: ${check(longLived)}`)
```

Python · main.py

```tin
# Binary trees: allocate and free many small trees (the benchmarks-game shape).

def make(depth):
    # a node is a (left, right) tuple; None is the empty tree
    if depth == 0:
        return (None, None)
    return (make(depth - 1), make(depth - 1))

def check(t):
    if t is None:
        return 0
    left, right = t
    return 1 + check(left) + check(right)

max_depth = 16
stretch = max_depth + 1
print(f"stretch tree of depth {stretch} check: {check(make(stretch))}")
long_lived = make(max_depth)
for depth in range(4, max_depth + 1, 2):
    iterations = 1 << (max_depth - depth + 4)
    total = 0
    for i in range(iterations):
        total += check(make(depth))
    print(f"{iterations} trees of depth {depth} check: {total}")
print(f"long lived tree of depth {max_depth} check: {check(long_lived)}")
```

Rust · main.rs

```tin
// Binary trees: allocate and free many small trees (the benchmarks-game shape).

enum Tree {
    Empty,
    Node(Box<Tree>, Box<Tree>),
}

fn make(depth: i32) -> Tree {
    if depth == 0 {
        Tree::Node(Box::new(Tree::Empty), Box::new(Tree::Empty))
    } else {
        Tree::Node(Box::new(make(depth - 1)), Box::new(make(depth - 1)))
    }
}

fn check(t: &Tree) -> i32 {
    match t {
        Tree::Empty => 0,
        Tree::Node(left, right) => 1 + check(left) + check(right),
    }
}

fn main() {
    let max_depth = std::hint::black_box(16);
    let stretch = max_depth + 1;
    println!("stretch tree of depth {} check: {}", stretch, check(&make(stretch)));
    let long_lived = make(max_depth);
    let mut depth = 4;
    while depth <= max_depth {
        let iterations = 1 << (max_depth - depth + 4);
        let mut total = 0;
        for _ in 0..iterations {
            total += check(&make(depth));
        }
        println!("{} trees of depth {} check: {}", iterations, depth, total);
        depth += 2;
    }
    println!("long lived tree of depth {} check: {}", max_depth, check(&long_lived));
}
```

**words — Strings: build a text, split it, count words in a map, write JSON by hand.

Every version prints `6999999 chars, 512 distinct words, json 7169 chars, top suneka x2080`

Tin · main.tin

```tin
// Strings: build a text, split it, count words in a map, write JSON by hand.

/// Park-Miller "minimal standard" random numbers (Schrage's method: never overflows 32 bits).
fn nextRand(s: int): int {
  let t = 16807 * (s % 127773) - 2836 * (s / 127773)
  if t <= 0 { t + 2147483647 } else { t }
}

fn main() {
  let syl = ["ka", "to", "ri", "ne", "su", "lo", "mi", "pa"]
  var seed = 42
  var parts: string[] = []
  for i in 0..1000000 {
    seed = nextRand(seed)
    let r = seed % 512
    parts.push(syl[r % 8] + syl[r / 8 % 8] + syl[r / 64])
  }
  let text = join(parts, " ")

  var counts: Map<string, int> = newMap()
  for w in text.split(" ") {
    counts.set(w, counts.get(w).or(0) + 1)
  }

  var fields: string[] = []
  var best = ""
  var bestN = 0
  for k in sort(counts.keys()) {
    let n = counts.get(k).or(0)
    fields.push("\"{k}\":{n}")
    if n > bestN {
      best = k
      bestN = n
    }
  }
  let json = "\{" + join(fields, ",") + "\}"
  print("{text.len} chars, {counts.size()} distinct words, json {json.len} chars, top {best} x{bestN}")
}
```

JavaScript · main.js

```tin
// Strings: build a text, split it, count words in a map, write JSON by hand.

/** Park-Miller "minimal standard" random numbers (Schrage's method: never overflows 32 bits). */
function nextRand(s) {
  const t = 16807 * (s % 127773) - 2836 * Math.floor(s / 127773)
  return t <= 0 ? t + 2147483647 : t
}

const syl = ['ka', 'to', 'ri', 'ne', 'su', 'lo', 'mi', 'pa']
let seed = 42
const parts = []
for (let i = 0; i < 1000000; i++) {
  seed = nextRand(seed)
  const r = seed % 512
  parts.push(syl[r % 8] + syl[Math.floor(r / 8) % 8] + syl[Math.floor(r / 64)])
}
const text = parts.join(' ')

const counts = new Map()
for (const w of text.split(' ')) counts.set(w, (counts.get(w) ?? 0) + 1)

const fields = []
let best = ''
let bestN = 0
for (const k of [...counts.keys()].sort()) {
  const n = counts.get(k)
  fields.push(`"${k}":${n}`)
  if (n > bestN) { best = k; bestN = n }
}
const json = '{' + fields.join(',') + '}'
console.log(`${text.length} chars, ${counts.size} distinct words, json ${json.length} chars, top ${best} x${bestN}`)
```

Python · main.py

```tin
# Strings: build a text, split it, count words in a map, write JSON by hand.

def next_rand(s):
    """Park-Miller "minimal standard" random numbers (Schrage's method: never overflows 32 bits)."""
    t = 16807 * (s % 127773) - 2836 * (s // 127773)
    return t + 2147483647 if t <= 0 else t

syl = ["ka", "to", "ri", "ne", "su", "lo", "mi", "pa"]
seed = 42
parts = []
for i in range(1000000):
    seed = next_rand(seed)
    r = seed % 512
    parts.append(syl[r % 8] + syl[r // 8 % 8] + syl[r // 64])
text = " ".join(parts)

counts = {}
for w in text.split(" "):
    counts[w] = counts.get(w, 0) + 1

fields = []
best = ""
best_n = 0
for k in sorted(counts):
    n = counts[k]
    fields.append(f'"{k}":{n}')
    if n > best_n:
        best, best_n = k, n
json = "{" + ",".join(fields) + "}"
print(f"{len(text)} chars, {len(counts)} distinct words, json {len(json)} chars, top {best} x{best_n}")
```

Rust · main.rs

```tin
// Strings: build a text, split it, count words in a map, write JSON by hand.
use std::collections::HashMap;

/// Park-Miller "minimal standard" random numbers (Schrage's method: never overflows 32 bits).
fn next_rand(s: i32) -> i32 {
    let t = 16807 * (s % 127773) - 2836 * (s / 127773);
    if t <= 0 { t + 2147483647 } else { t }
}

fn main() {
    let syl = ["ka", "to", "ri", "ne", "su", "lo", "mi", "pa"];
    let mut seed = std::hint::black_box(42);
    let mut parts: Vec<String> = Vec::new();
    for _ in 0..1000000 {
        seed = next_rand(seed);
        let r = (seed % 512) as usize;
        parts.push(format!("{}{}{}", syl[r % 8], syl[r / 8 % 8], syl[r / 64]));
    }
    let text = parts.join(" ");

    let mut counts: HashMap<&str, i32> = HashMap::new();
    for w in text.split(' ') {
        *counts.entry(w).or_insert(0) += 1;
    }

    let mut keys: Vec<&&str> = counts.keys().collect();
    keys.sort();
    let mut fields: Vec<String> = Vec::new();
    let (mut best, mut best_n) = ("", 0);
    for k in keys {
        let n = counts[*k];
        fields.push(format!("\"{}\":{}", k, n));
        if n > best_n { best = k; best_n = n; }
    }
    let json = format!("{{{}}}", fields.join(","));
    println!("{} chars, {} distinct words, json {} chars, top {} x{}", text.len(), counts.len(), json.len(), best, best_n);
}
```
