Benchmarks
Four languages, same programs, same output.
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 on this page is read
from bench/results/latest.json when the site is built.
Reading it honestly
- Rust is fastest on 7 of 8. It compiles ahead of time to native code with no
runtime around it, and its process starts in a few milliseconds. On Node, Tin's WebAssembly is compiled again by
the JS engine, and every Tin integer
+ - *is overflow-checked and every index bounds-checked. - Without Node, Tin 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. That is
tin build --native: the same checked WebAssembly turned into C by wasm2c and compiled by the system C compiler (table below). It cannot runagentyet: agents and tasks need the JavaScript host. sortis not like-for-like. Tin'ssort()onint[]is a radix sort; Rust's and JavaScript'ssortcompare elements. Part of Tin's lead on that row is the algorithm, not the compiler.sortBy, which compares, is the like-for-like number.- Tin beats Python on 8 of 8 and JavaScript on 4 of 8. Tin and
JavaScript run on the same engine, so on number crunching they land close together. Tin also pays a fixed
startup cost to load its runtime: see
hello. - Where Tin loses to JavaScript or Python (computed from the data, not chosen):
agent,mandelbrot,nbody,trees. Why, measured:agent: the two sides don't run the same model. Tin's built-in offlinemockalso estimates tokens (so budgets can be tried offline) and fills each tool's input from its JSON Schema; the hand-written JavaScript loop's model only reads numbers from the prompt, and that loop has no typed tool input, turn limit, token budget or rollback. With the JavaScript loop's model plugged into Tin's runtime as a provider, the program takes 52.5 ms against 47 ms for the JavaScript loop; Tin's mock alone takes 35 ms for the bench's 100,000 model calls (bench/agent-parts.mjs).trees: Tin frees each node the moment it dies; JavaScript's collector frees young objects in bulk (and keeps 4× the memory to do it).nbody: everyb.x[i]is bounds-checked, and V8 removes more repeated loads from JavaScript than from WebAssembly.mandelbrot,hello: within a few percent, the fixed cost of loading Tin's runtime into Node. - Why Tin anyway. Not raw speed. Agents, tools and their permissions are checked by the compiler, the same program runs in the browser and the CLI, and the speed stays in JavaScript's range while overflow and out-of-bounds reads are errors instead of silent bugs.
Run time
Median of 7 runs, min–max underneath. Lower is better. The fastest language per row is bold.
| program | Tin | JavaScript | Python | Rust | Tin vs JS | Tin vs Python | Tin vs Rust |
|---|---|---|---|---|---|---|---|
| hello | 26 ms26 ms–28 ms | 24 ms24 ms–26 ms | 14 ms14 ms–14 ms | 3.2 ms3.1 ms–3.5 ms | 1.1× slower | 1.9× slower | 8.2× slower |
| agent | 112 ms111 ms–114 ms | 72 ms71 ms–74 ms | 184 ms183 ms–188 ms | 32 ms30 ms–34 ms | 1.5× slower | 1.6× faster | 3.5× slower |
| fib | 53 ms52 ms–54 ms | 99 ms98 ms–100 ms | 667 ms663 ms–676 ms | 25 ms25 ms–26 ms | 1.9× faster | 12× faster | 2.1× slower |
| mandelbrot | 72 ms70 ms–76 ms | 69 ms69 ms–71 ms | 1.22 s1.21 s–1.25 s | 45 ms45 ms–47 ms | 1.1× slower | 17× faster | 1.6× slower |
| nbody | 55 ms54 ms–58 ms | 47 ms46 ms–47 ms | 1.13 s1.12 s–1.14 s | 14 ms13 ms–14 ms | 1.2× slower | 21× faster | 4.0× slower |
| sieve | 78 ms75 ms–82 ms | 96 ms94 ms–104 ms | 1.62 s1.60 s–1.72 s | 20 ms19 ms–21 ms | 1.2× faster | 21× faster | 3.9× slower |
| sort | 74 ms73 ms–77 ms | 366 ms364 ms–375 ms | 834 ms825 ms–842 ms | 35 ms34 ms–36 ms | 5.0× faster | 11× faster | 2.1× slower |
| trees | 128 ms127 ms–130 ms | 122 ms121 ms–123 ms | 758 ms755 ms–773 ms | 276 ms267 ms–290 ms | 1.0× slower | 5.9× faster | 2.2× faster |
| words | 109 ms108 ms–114 ms | 177 ms176 ms–185 ms | 314 ms305 ms–320 ms | 46 ms45 ms–47 ms | 1.6× faster | 2.9× faster | 2.4× slower |
Tin without Node
Whole process, startup included, median; peak RSS underneath. Tin WASI is
tin build --target wasi run by wasmtime 50.0.1 (which compiles the module on every
run). Tin native is tin build --native: wasm2c, then Apple clang version 21.0.0 at
-O2. Both keep every overflow, bounds and memory check. — means the target refuses the program.
| program | Tin on Node | Tin WASI | Tin native | JavaScript | Rust | native vs JS | native vs Rust |
|---|---|---|---|---|---|---|---|
| hello | 26 ms55 MB | 5.3 ms11 MB | 2.9 ms2 MB | 24 ms53 MB | 3.2 ms2 MB | 8.3× faster | 1.1× faster |
| agent | 112 ms81 MB | — | — | 72 ms71 MB | 32 ms3 MB | — | — |
| fib | 53 ms58 MB | 76 ms11 MB | 36 ms2 MB | 99 ms57 MB | 25 ms2 MB | 2.7× faster | 1.4× slower |
| mandelbrot | 72 ms58 MB | 52 ms11 MB | 44 ms2 MB | 69 ms60 MB | 45 ms2 MB | 1.6× faster | 1.0× faster |
| nbody | 55 ms58 MB | 57 ms11 MB | 21 ms2 MB | 47 ms60 MB | 14 ms2 MB | 2.3× faster | 1.5× slower |
| sieve | 78 ms68 MB | 33 ms20 MB | 25 ms11 MB | 96 ms134 MB | 20 ms12 MB | 3.9× faster | 1.2× slower |
| sort | 74 ms97 MB | 41 ms50 MB | 28 ms41 MB | 366 ms139 MB | 35 ms27 MB | 13× faster | 1.2× faster |
| trees | 128 ms67 MB | 166 ms19 MB | 103 ms10 MB | 122 ms107 MB | 276 ms10 MB | 1.2× faster | 2.7× faster |
| words | 109 ms142 MB | 94 ms94 MB | 58 ms85 MB | 177 ms212 MB | 46 ms49 MB | 3.0× faster | 1.3× slower |
Run time inside the process
The same runs timed inside each process (load + compile + run, no interpreter or Node startup), so startup is out of the picture. Rust has no separate number: its process starts in about 3.2 ms.
| program | Tin | JavaScript | Python | Tin vs JS | Tin vs Python |
|---|---|---|---|---|---|
| hello | 2.2 ms2.1 ms–2.4 ms | 1.5 ms1.5 ms–1.6 ms | 1.6 ms1.6 ms–1.7 ms | 1.5× slower | 1.4× slower |
| agent | 86 ms85 ms–87 ms | 47 ms47 ms–47 ms | 171 ms170 ms–174 ms | 1.8× slower | 2.0× faster |
| fib | 28 ms28 ms–29 ms | 75 ms75 ms–76 ms | 654 ms650 ms–662 ms | 2.6× faster | 23× faster |
| mandelbrot | 46 ms46 ms–50 ms | 45 ms45 ms–47 ms | 1.21 s1.20 s–1.24 s | 1.0× slower | 26× faster |
| nbody | 30 ms29 ms–30 ms | 22 ms22 ms–22 ms | 1.12 s1.11 s–1.12 s | 1.3× slower | 38× faster |
| sieve | 50 ms49 ms–53 ms | 71 ms69 ms–76 ms | 1.60 s1.59 s–1.70 s | 1.4× faster | 32× faster |
| sort | 49 ms48 ms–50 ms | 341 ms339 ms–350 ms | 751 ms746 ms–760 ms | 7.0× faster | 15× faster |
| trees | 103 ms103 ms–103 ms | 96 ms95 ms–97 ms | 745 ms742 ms–760 ms | 1.1× slower | 7.2× faster |
| words | 84 ms82 ms–87 ms | 149 ms148 ms–156 ms | 294 ms287 ms–300 ms | 1.8× faster | 3.5× faster |
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 |
Compile time
Python and JavaScript compile as they run, so their compile cost is inside their run time.
| 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 |
Method
- Machine
- Apple M5 Pro, 15 cores, 24 GB, macOS 27.2 arm64. Measured 2026-11-15 22:21 UTC.
- Versions
- Tin 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)
- Runs
- 7 timed runs after 1 warm-up per program and language
- Order
- interleaved: run i of every language, then run i + 1 of every language, so load on the machine hits every language alike
- Noise
- a 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.
- Timing
- wall 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)
- Memory
- peak RSS from /usr/bin/time -l, max over runs
- Tin
- compiled once with `tin build`; timed runs execute the .wasm with bench/tin-run.mjs on Node
- Rust
- rustc -C opt-level=3, standard library only
- Tin WASI
- tin build --target wasi, run by `wasmtime run` (wall time includes Cranelift compiling the module); not for programs with agents
- Tin native
- tin build --native: wasm2c + cc -O2, one executable; not for programs with agents
- Python
- CPython, no third-party packages. Newer CPython (3.11+) is noticeably faster at loops and calls than 3.9.
- JavaScript
- Node, plain .js
- Rerun it
npm install && npm run bench(needs Node ≥ 24, python3, rustc). One machine, one run of the harness, other programs open: treat differences under ~10% as noise.
The programs
hello — hello
Every version prints: hello
fn main() {
print("hello")
}
console.log('hello')
print("hello")
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
// 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}")
}
// 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}`)
# 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}")
// 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
// 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)}")
}
// Recursive Fibonacci: function-call overhead.
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2)
}
console.log(`fib(36) = ${fib(36)}`)
# 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)}")
// 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
// 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")
}
// 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`)
# 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")
// 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
// 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))
}
// 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))
# 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}")
// 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
// 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}")
}
// 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}`)
# 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}")
// 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
// 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}")
}
// 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}`)
# 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}")
// 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
// 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)}")
}
// 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)}`)
# 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)}")
// 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
// 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}")
}
// 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}`)
# 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}")
// 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);
}