x2c

A comparison, measured

Programming language shootout.

Ten problems, two styles, and the choices behind the measurements.

Recorded on an Apple M4 Max, 12 November 2026 UTC. Local inputs, twelve x2c samples; other-language results use an earlier calibration. These are local comparisons, not published Benchmarks Game results.

A small numerical loop and a DNA-processing pipeline ask different things of a language. One spends its time on arithmetic. Another creates strings, looks up keys, and moves bytes between buffers. A single score hides those differences.

This experiment starts with ten Computer Language Benchmarks Game problems. Each has two x2c implementations: an idiomatic version built with ordinary collections and APIs, and a tuned version that specializes the work where it matters. The question is what changes when we move between those styles, and how much code that change needs.

In the recorded November 2026 local-input snapshot, across the eight problems shared by all eight implementation columns, tuned x2c takes 1.20 times the C elapsed time, with 0.89 times the C source lines. Those are geometric means of matched problem ratios. The individual programs tell a more useful story than that summary.

Start with the individual problems

Elapsed time relative to C for ten problems, comparing idiomatic and tuned x2c.
Ten problems; lower is faster. The dashed line is the C time for each problem. Ratios use a logarithmic scale.

Tuning makes its largest differences in the text-processing programs. On k-nucleotide, elapsed time falls from 102.8 ms to 17.4 ms. FASTA falls from 22.6 ms to 4.4 ms, and reverse-complement from 12.4 ms to 2.5 ms. Each pair solves the same problem specification, but changes how the program represents or moves its data.

Other pairs barely move. The two binary-trees sources are identical; their 26.6 ms and 26.8 ms medians are separate measurements of that same source. Pi digits also changes little: 281.5 ms becomes 269.2 ms. There is no single transformation that explains every row.

These are small local inputs. Mandelbrot's C baseline is 2.8 ms, while pi digits takes 263.4 ms. A ratio should be read with its absolute time; it does not tell us how much time a larger application would save.

Put the representation where the work is

The n-body simulation keeps five bodies moving under mutual gravity. The idiomatic implementation uses heap objects and an Array of body pairs. The tuned version keeps the five bodies in a native array of structs and visits each pair with two loops. It still uses Vec3 methods and required reference parameters for the physics.

On this input, n-body goes from 72.9 ms in 102 source lines to 33.2 ms in 82 lines. The C program takes 32.8 ms. Here, making the fixed shape explicit also removes code: the tuned program does not need a separate collection of pair objects.

K-nucleotide makes a different representation choice. Both implementations count all sliding windows for their requested lengths. The idiomatic program creates a String key for each window and updates a general Map. The tuned program uses MapSubInt, whose keys borrow spans of the original sequence:

MapSubInt counts = MapSubInt.new();
for (int i = 0; i + width <= sequence.len(); i++)
  counts.increment(sequence.substring(i, width));

The tuned program retains the sequence while those views are in use. It materializes strings where the frequency report needs them. This removes repeated key creation from the counting loop without replacing the required growing-map algorithm. Its 17.4 ms still exceeds the C baseline's 9.3 ms; the shorter implementation does not erase every cost.

Move bytes in batches

The idiomatic reverse-complement program reads FASTA lines, collects each sequence in a Buffer, and builds its output one line at a time. The tuned program reads 16 KiB chunks with fread, uses a complement lookup table, transforms its typed character buffer in place, and batches output before calling write_all.

That version grows from 47 to 67 source lines, while its measured time falls from 12.4 to 2.5 ms. The added code handles chunk boundaries, headers, and output buffering. It is useful code to write when this work matters; it is also more code to understand and maintain.

FASTA follows a similar route. The ordinary version builds output lines with a Buffer and stores probability choices as objects. The tuned version uses typed probability storage and a native output buffer. It grows from 65 to 82 lines and drops from 22.6 to 4.4 ms. These comparisons change several implementation details together. They do not isolate the contribution of each change.

Speed does not have one source-size cost

Source lines for ten problems, comparing idiomatic and tuned x2c.
The same ten problems in the same order. Counts exclude blank lines and comments; the axis is linear.

Tuned n-body and spectral-norm are both shorter than their idiomatic counterparts. The text-processing variants usually add code. Regex-redux grows from 61 to 97 lines: it keeps PCRE2 and independent pattern-counting threads, but uses borrowed match-data blocks instead of constructing capture Lists, plus typed buffers for substitutions. Its time falls from 26.4 to 13.3 ms.

Pi digits already delegates arbitrary-precision arithmetic to GMP in both versions. The tuned version uses fused multiply-add and multiply-subtract operations to avoid intermediate products; it retains both extracts required by the problem. This is a smaller change, and the measured difference is smaller too.

Source lines here mean nonblank lines after language-aware comment removal. They are a way to inspect the amount of source, not a measurement of clarity. The recorded dataset also includes normalized gzip bytes. On the shared cohort, tuned x2c uses 0.89 times C's source lines but 1.11 times its compressed source bytes. The answer changes with the measure.

Place the results beside the other programs

Eight-implementation summary of elapsed time relative to C and source lines relative to Python.
Geometric means across the eight shared problems. Runtime uses a log scale; source size uses a linear scale. Lower values mean less time or fewer lines.

This view includes only the eight problems with an entry in every column. Tuned x2c's elapsed-time ratio is 1.20; Rust's is 1.17. Idiomatic x2c is 2.82 relative to C, with 1.19 times Python's source lines; tuned x2c uses 1.29 times Python's lines.

These are selected implementations, not rankings of what each language can do. The source choices, libraries, process model, and input sizes all matter. Java starts a fresh JVM for each sample, including startup and JIT compilation; the warmup process does not warm the next JVM. Its number is not a steady-state server measurement.

The missing contributions also matter. K-nucleotide has no Rust, C++, Go, or Java entry in this environment. Binary-trees has no Python entry. Those problems remain visible in the x2c comparisons above, but are excluded from the shared summary rather than silently given substitute scores.

What was measured

The figures use the recorded 12 November 2026 UTC snapshot on an Apple M4 Max, with the suite's local input profile. Each x2c result is the median of twelve fresh processes after one warmup. Foreign-language measurements come from the pinned earlier calibration; they were not rerun alongside these x2c samples. The canonical-size suite remains unrun.

The measured source revision is ccc7e475869cf93f91637f283761a57dfd92715b. Published commit 2ef0360087 holds the same benchmark sources. The explanations above describe those measured sources. Some current example sources have since changed. The downloadable results, measurements, and provenance identify the snapshot, its inputs, and included entries.

The useful next step is to read a pair of implementations for a workload you recognize. Below are the complete current programs, followed by commands for checking them locally. The charts describe the recorded snapshot, not a new run of those current files.

Measured benchmark sourcesFigure provenanceFull results and inputsMeasurements CSV

Read the complete programs.

These are the current sources. Open a problem to read either version or compare both. The article above explains the recorded snapshot.

01 / 10

n-body

Advance five bodies under mutual gravity, then report the system's energy.

Problem specification
Read and compare source
Read n-body source
Idiomatic x2c / main.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 *
 * Adapted from Christoph Bauer's contributed C implementation.
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define PI 3.141592653589793
#define SOLAR_MASS (4 * PI * PI)
#define DAYS_PER_YEAR 365.24

class Vec3 { double x, y, z; };
class Body { Vec3 position, velocity; double mass; } *;
class Pair { Body first, second; } *;

int main(int argc, char **argv) {
  Array bodies = _bodies();
  foreach (Body body in bodies) {
    body.velocity = body.velocity.scale(DAYS_PER_YEAR);
    body.mass *= SOLAR_MASS;
  }
  _offset_momentum(bodies);
  printf("%.9f\n", _energy(bodies));
  Array pairs = _pairs(bodies);
  for (int i = atoi(argv[1]); i; i--) _advance(bodies, pairs, 0.01);
  printf("%.9f\n", _energy(bodies));
  return 0;
}

static void Pair.init(Pair pair, Body first, Body second) {
  pair.first = first;
  pair.second = second;
}

static void Body.init(Body body, Vec3 position, Vec3 velocity, double mass) {
  body.position = position;
  body.velocity = velocity;
  body.mass = mass;
}

static Array _bodies(void) => [
  Body.new(Vec3.new(0, 0, 0), Vec3.new(0, 0, 0), 1),
  Body.new(
    Vec3.new(4.84143144246472090, -1.16032004402742839, -0.103622044471123109),
    Vec3.new(1.66007664274403694e-03, 7.69901118419740425e-03,
      -6.90460016972063023e-05), 9.54791938424326609e-04),
  Body.new(
    Vec3.new(8.34336671824457987, 4.12479856412430479, -0.403523417114321381),
    Vec3.new(-2.76742510726862411e-03, 4.99852801234917238e-03,
      2.30417297573763929e-05), 2.85885980666130812e-04),
  Body.new(
    Vec3.new(12.8943695621391310, -15.1111514016986312, -0.223307578892655734),
    Vec3.new(2.96460137564761618e-03, 2.37847173959480950e-03,
      -2.96589568540237556e-05), 4.36624404335156298e-05),
  Body.new(
    Vec3.new(15.3796971148509165, -25.9193146099879641, 0.179258772950371181),
    Vec3.new(2.68067772490389322e-03, 1.62824170038242295e-03,
      -9.51592254519715870e-05), 5.15138902046611451e-05)
];

static void _offset_momentum(Array bodies) {
  Vec3 momentum = Vec3.new(0, 0, 0);
  foreach (Body body in bodies)
    momentum = momentum.add_scaled(body.velocity, body.mass);
  Body sun = bodies[0];
  sun.velocity = momentum.scale(-1.0 / SOLAR_MASS);
}

static inline Vec3 Vec3.scale(Vec3 a, double s) =>
  Vec3.new(a.x * s, a.y * s, a.z * s);

static inline Vec3 Vec3.add_scaled(Vec3 a, Vec3 b, double s) =>
  Vec3.new(a.x + b.x * s, a.y + b.y * s, a.z + b.z * s);

static void _advance(Array bodies, Array pairs, double dt) {
  foreach (Pair pair in pairs) pair.first.attract(pair.second, dt);
  foreach (Body body in bodies) body.drift(dt);
}

/* Body identities stay fixed. Resolve the ten interaction pairs once. */
static Array _pairs(Array bodies) {
  Array pairs = [];
  for (int i = 0; i < bodies.len(); i++) {
    Body first = bodies[i];
    for (int j = i + 1; j < bodies.len(); j++) {
      Body second = bodies[j];
      pairs.push(Pair.new(first, second));
    }
  }
  return pairs;
}

static void Body.attract(Body body, Body other, double dt) {
  Vec3 d = body.position.sub(other.position);
  double distance = sqrt(d.dot(d));
  double magnitude = dt / (distance * distance * distance);
  body.velocity = body.velocity.add_scaled(d.scale(other.mass), -magnitude);
  other.velocity = other.velocity.add_scaled(d.scale(body.mass), magnitude);
}

static inline Vec3 Vec3.sub(Vec3 a, Vec3 b) =>
  Vec3.new(a.x - b.x, a.y - b.y, a.z - b.z);

static inline double Vec3.dot(Vec3 a, Vec3 b) =>
  a.x * b.x + a.y * b.y + a.z * b.z;

static void Body.drift(Body body, double dt) =>
  body.position = body.position.add_scaled(body.velocity, dt);

static double _energy(Array bodies) {
  double total = 0.0;
  for (int i = 0; i < bodies.len(); i++) {
    Body body = bodies[i];
    total += 0.5 * body.mass * body.velocity.dot(body.velocity);
    for (int j = i + 1; j < bodies.len(); j++) {
      Body other = bodies[j];
      Vec3 d = body.position.sub(other.position);
      total -= body.mass * other.mass / sqrt(d.dot(d));
    }
  }
  return total;
}
Tuned x2c / tuned.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 *
 * Adapted from Christoph Bauer's contributed C implementation.
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define PI 3.141592653589793
#define SOLAR_MASS (4 * PI * PI)
#define DAYS_PER_YEAR 365.24

class Vec3 { double x, y, z; };
typedef struct Body { Vec3 position, velocity; double mass; } Body;

int main(int argc, char **argv) {
  Body bodies[5] = {
    Body.new(Vec3.new(0, 0, 0), Vec3.new(0, 0, 0), 1),
    Body.new(
      Vec3.new(4.84143144246472090, -1.16032004402742839, -0.103622044471123109),
      Vec3.new(1.66007664274403694e-03, 7.69901118419740425e-03,
        -6.90460016972063023e-05), 9.54791938424326609e-04),
    Body.new(
      Vec3.new(8.34336671824457987, 4.12479856412430479, -0.403523417114321381),
      Vec3.new(-2.76742510726862411e-03, 4.99852801234917238e-03,
        2.30417297573763929e-05), 2.85885980666130812e-04),
    Body.new(
      Vec3.new(12.8943695621391310, -15.1111514016986312, -0.223307578892655734),
      Vec3.new(2.96460137564761618e-03, 2.37847173959480950e-03,
        -2.96589568540237556e-05), 4.36624404335156298e-05),
    Body.new(
      Vec3.new(15.3796971148509165, -25.9193146099879641, 0.179258772950371181),
      Vec3.new(2.68067772490389322e-03, 1.62824170038242295e-03,
        -9.51592254519715870e-05), 5.15138902046611451e-05)
  };
  for (int i = 0; i < 5; i++) {
    Body *body = &bodies[i];
    body.velocity = body.velocity.scale(DAYS_PER_YEAR);
    body.mass *= SOLAR_MASS;
  }
  _offset_momentum(bodies);
  printf("%.9f\n", _energy(bodies));
  for (int i = atoi(argv[1]); i; i--) _advance(bodies, 0.01);
  printf("%.9f\n", _energy(bodies));
  return 0;
}

static Body Body.new(Vec3 position, Vec3 velocity, double mass) =>
  (Body) { position, velocity, mass };

static void _offset_momentum(Body *bodies) {
  Vec3 momentum = Vec3.new(0, 0, 0);
  for (int i = 0; i < 5; i++)
    momentum = momentum.add_scaled(bodies[i].velocity, bodies[i].mass);
  bodies[0].velocity = momentum.scale(-1.0 / SOLAR_MASS);
}

static inline Vec3 Vec3.scale(Vec3 a, double s) =>
  Vec3.new(a.x * s, a.y * s, a.z * s);

static inline Vec3 Vec3.add_scaled(Vec3 a, Vec3 b, double s) =>
  Vec3.new(a.x + b.x * s, a.y + b.y * s, a.z + b.z * s);

static void _advance(Body *bodies, double dt) {
  for (int i = 0; i < 5; i++)
    for (int j = i + 1; j < 5; j++) bodies[i].attract(bodies[j], dt);
  for (int i = 0; i < 5; i++) bodies[i].drift(dt);
}

static void Body.attract(Body &body, Body &other, double dt) {
  Vec3 d = body.position.sub(other.position);
  double distance = sqrt(d.dot(d));
  double magnitude = dt / (distance * distance * distance);
  body.velocity = body.velocity.add_scaled(d.scale(other.mass), -magnitude);
  other.velocity = other.velocity.add_scaled(d.scale(body.mass), magnitude);
}

static inline Vec3 Vec3.sub(Vec3 a, Vec3 b) =>
  Vec3.new(a.x - b.x, a.y - b.y, a.z - b.z);

static inline double Vec3.dot(Vec3 a, Vec3 b) =>
  a.x * b.x + a.y * b.y + a.z * b.z;

static void Body.drift(Body &body, double dt) =>
  body.position = body.position.add_scaled(body.velocity, dt);

static double _energy(Body *bodies) {
  double total = 0.0;
  for (int i = 0; i < 5; i++) {
    Body body = bodies[i];
    total += 0.5 * body.mass * body.velocity.dot(body.velocity);
    for (int j = i + 1; j < 5; j++) {
      Body other = bodies[j];
      Vec3 d = body.position.sub(other.position);
      total -= body.mass * other.mass / sqrt(d.dot(d));
    }
  }
  return total;
}

02 / 10

spectral norm

Estimate an implicit matrix's spectral norm through repeated matrix-vector products.

Problem specification
Read and compare source
Read spectral norm source
Idiomatic x2c / main.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 *
 * Adapted from the contributions recorded in ../../benchmarks.json.
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

class Rows {
  Array input, output;
  int first, last, transpose;
  Thread worker;
} *;

int main(int argc, char **argv) {
  int n = argc > 1 ? atoi(argv[1]) : 100;
  Array u = [], v = [], scratch = [];
  for (int i = 0; i < n; i++) {
    u.push(1.0);
    v.push(0.0);
    scratch.push(0.0);
  }
  for (int i = 0; i < 10; i++) {
    _ata_times(u, v, scratch);
    _ata_times(v, u, scratch);
  }
  double uv = 0.0, vv = 0.0;
  for (int i = 0; i < n; i++) {
    uv += u[i].double() * v[i].double();
    vv += v[i].double() * v[i].double();
  }
  printf("%.9f\n", sqrt(uv / vv));
  return 0;
}

static void _ata_times(Array input, Array output, Array scratch) {
  _multiply(input, scratch, 0);
  _multiply(scratch, output, 1);
}

static void _multiply(Array input, Array output, int transpose) {
  int n = input.len(), workers = n < 6 ? n : 6;
  auto {
    if (n < 256) {
      _calculate_rows(Rows.new(input, output, 0, n, transpose));
      return;
    }
    Array batches = [];
    for (int worker = 0; worker < workers; worker++) {
      Rows rows = Rows.new(input, output,
        n * worker / workers, n * (worker + 1) / workers, transpose);
      rows.worker = Thread.start(_calculate_rows, rows);
      batches.push(rows);
    }
    foreach (Rows rows in batches) {
      rows.worker.join();
      rows.worker.free();
    }
  }
}

static void Rows.init(Rows rows, Array input, Array output,
  int first, int last, int transpose) {
  rows.input = input;
  rows.output = output;
  rows.first = first;
  rows.last = last;
  rows.transpose = transpose;
}

static Var _calculate_rows(Var input) {
  Rows rows = input;
  int n = rows.input.len();
  for (int i = rows.first; i < rows.last; i++) {
    double sum = 0.0;
    for (int j = 0; j < n; j++)
      sum += (rows.transpose ? _entry(j, i) : _entry(i, j)) *
        rows.input[j].double();
    rows.output[i] = sum;
  }
  return void;
}

static double _entry(int i, int j) =>
  1.0 / ((i + j) * (i + j + 1) / 2 + i + 1);
Tuned x2c / tuned.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 *
 * Adapted from the contributions recorded in ../../benchmarks.json.
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "typed-array.x"

int main(int argc, char **argv) {
  int n = argc > 1 ? atoi(argv[1]) : 100;
  ArrayDbl u = ArrayDbl.new(), v = ArrayDbl.new(), scratch = ArrayDbl.new();
  for (int i = 0; i < n; i++) {
    u.push(1.0);
    v.push(0.0);
    scratch.push(0.0);
  }
  for (int i = 0; i < 10; i++) {
    _ata_times(u, v, scratch);
    _ata_times(v, u, scratch);
  }
  double uv = 0.0, vv = 0.0;
  for (int i = 0; i < n; i++) {
    uv += u[i] * v[i];
    vv += v[i] * v[i];
  }
  printf("%.9f\n", sqrt(uv / vv));
  return 0;
}

static void _ata_times(ArrayDbl input, ArrayDbl output, ArrayDbl scratch) {
  _a_times(input, scratch);
  _at_times(scratch, output);
}

static void _a_times(ArrayDbl input, ArrayDbl output) =>
  _multiply(input, output, 0);

static void _at_times(ArrayDbl input, ArrayDbl output) =>
  _multiply(input, output, 1);

static void _multiply(ArrayDbl input, ArrayDbl output, int transpose) {
  int n = input.len();
  if (n < 500) {
    _rows(input, output, 0, n, transpose);
    return;
  }
  auto {
    Array jobs = [];
    for (int worker = 0; worker < 6; worker++)
      jobs.push(%!() => _rows(input, output,
        n * worker / 6, n * (worker + 1) / 6, transpose));
    Thread.run(jobs);
  }
}

static void _rows(ArrayDbl input, ArrayDbl output,
  int first, int last, int transpose) {
  int n = input.len();
  for (int i = first; i < last; i++) {
    double sum = 0.0;
    int denominator = transpose ? _entry(0, i) : _entry(i, 0);
    for (int j = 0; j < n; j++) {
      sum += (1.0 / denominator) * input[j];
      // Adjacent denominators differ by i + j + 1 (A), or i + j + 2 (At).
      denominator += i + j + 1 + transpose;
    }
    output[i] = sum;
  }
}

static int _entry(int i, int j) =>
  (i + j) * (i + j + 1) / 2 + i + 1;

03 / 10

fannkuch-redux

Enumerate permutations, reverse prefixes, and report the checksum and largest flip count.

Problem specification
Read and compare source
Read fannkuch-redux source
Idiomatic x2c / main.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 *
 * Adapted from the contributions recorded in ../../benchmarks.json.
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <stdio.h>
#include <stdlib.h>

class Chunk {
  int n, maximum, checksum;
  long first, last;
  Thread worker;
} *;

int main(int argc, char **argv) {
  int n = argc > 1 ? atoi(argv[1]) : 7;
  printf("Pfannkuchen(%d) = %d\n", n, _fannkuch(n));
  return 0;
}

static int _fannkuch(int n) {
  long total = 1;
  for (int i = 2; i <= n; i++) total *= i;
  int workers = n < 9 ? 1 : 6, maximum = 0, checksum = 0;
  auto {
    Array chunks = [];
    for (int worker = 0; worker < workers; worker++) {
      Chunk chunk = Chunk.new(n,
        total * worker / workers, total * (worker + 1) / workers);
      if (workers == 1) _run_chunk(chunk);
      else chunk.worker = Thread.start(_run_chunk, chunk);
      chunks.push(chunk);
    }
    foreach (Chunk chunk in chunks) {
      if (workers > 1) {
        chunk.worker.join();
        chunk.worker.free();
      }
      if (chunk.maximum > maximum) maximum = chunk.maximum;
      checksum += chunk.checksum;
    }
  }
  printf("%d\n", checksum);
  return maximum;
}

static void Chunk.init(Chunk chunk, int n, long first, long last) {
  chunk.n = n;
  chunk.first = first;
  chunk.last = last;
}

static Var _run_chunk(Var input) {
  Chunk chunk = input;
  Array permutation = [], working = [], counts = [];
  for (int i = 0; i < chunk.n; i++) {
    permutation.push(i);
    working.push(i);
    counts.push(i + 1);
  }
  if (chunk.first) _seek(permutation, counts, chunk.n, chunk.first);
  int maximum = 0, checksum = 0;
  for (long index = chunk.first; index < chunk.last; index++) {
    working.setslice(0, chunk.n, permutation);
    int flips = 0;
    for (int k = working[0].int(); k; k = working[0].int()) {
      for (int i = 0, j = k; i < j; i++, j--) {
        Var value = working[i];
        working[i] = working[j];
        working[j] = value;
      }
      flips++;
    }
    if (flips > maximum) maximum = flips;
    checksum += index % 2 ? -flips : flips;
    _advance(permutation, counts, chunk.n);
  }
  chunk.maximum = maximum;
  chunk.checksum = checksum;
  return void;
}

static void _seek(Array permutation, Array counts, int n, long index) {
  long factor = 1;
  for (int i = 2; i < n; i++) factor *= i;
  for (int r = n - 1; r > 0; r--) {
    int rotations = index / factor;
    index %= factor;
    counts[r] = r + 1 - rotations;
    for (int i = 0; i < rotations; i++) _rotate(permutation, r);
    factor /= r;
  }
}

static void _rotate(Array permutation, int last) {
  Var first = permutation[0];
  for (int i = 0; i < last; i++) permutation[i] = permutation[i + 1];
  permutation[last] = first;
}

static int _advance(Array permutation, Array counts, int n) {
  for (int r = 1; r < n; r++) {
    _rotate(permutation, r);
    int remaining = counts[r].int() - 1;
    counts[r] = remaining;
    if (remaining) return 1;
    counts[r] = r + 1;
  }
  return 0;
}
Tuned x2c / tuned.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 *
 * Adapted from the contributions recorded in ../../benchmarks.json.
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <stdio.h>
#include <stdlib.h>
#include "typed-array.x"

class Chunk {
  int n, maximum, checksum;
  long first, last;
  Thread worker;
} *;

int main(int argc, char **argv) {
  int n = argc > 1 ? atoi(argv[1]) : 7;
  printf("Pfannkuchen(%d) = %d\n", n, _fannkuch(n));
  return 0;
}

static int _fannkuch(int n) {
  long total = 1;
  for (int i = 2; i <= n; i++) total *= i;
  int workers = n < 9 ? 1 : 6, maximum = 0, checksum = 0;
  auto {
    Array chunks = [];
    for (int worker = 0; worker < workers; worker++) {
      Chunk chunk = Chunk.new(n,
        total * worker / workers, total * (worker + 1) / workers);
      if (workers == 1) _run_chunk(chunk);
      else chunk.worker = Thread.start(_run_chunk, chunk);
      chunks.push(chunk);
    }
    foreach (Chunk chunk in chunks) {
      if (workers > 1) {
        chunk.worker.join();
        chunk.worker.free();
      }
      if (chunk.maximum > maximum) maximum = chunk.maximum;
      checksum += chunk.checksum;
    }
  }
  printf("%d\n", checksum);
  return maximum;
}

static void Chunk.init(Chunk chunk, int n, long first, long last) {
  chunk.n = n;
  chunk.first = first;
  chunk.last = last;
}

static Var _run_chunk(Var input) {
  Chunk chunk = input;
  int n = chunk.n;
  ArrayInt permutation = ArrayInt.new(), working = ArrayInt.new();
  ArrayInt counts = ArrayInt.new();
  for (int i = 0; i < n; i++) {
    permutation.push(i);
    working.push(i);
    counts.push(i + 1);
  }
  if (chunk.first) _seek(permutation, counts, n, chunk.first);
  int maximum = 0, checksum = 0;
  for (long index = chunk.first; index < chunk.last; index++) {
    for (int i = 0; i < n; i++) working[i] = permutation[i];
    int flips = 0;
    for (int k = working[0]; k; k = working[0]) {
      for (int i = 0, j = k; i < j; i++, j--) {
        int value = working[i];
        working[i] = working[j];
        working[j] = value;
      }
      flips++;
    }
    if (flips > maximum) maximum = flips;
    checksum += index % 2 ? -flips : flips;
    _advance(permutation, counts, n);
  }
  chunk.maximum = maximum;
  chunk.checksum = checksum;
  return void;
}

static void _seek(ArrayInt permutation, ArrayInt counts, int n, long index) {
  long factor = 1;
  for (int i = 2; i < n; i++) factor *= i;
  for (int r = n - 1; r > 0; r--) {
    int rotations = index / factor;
    index %= factor;
    counts[r] = r + 1 - rotations;
    for (int i = 0; i < rotations; i++) _rotate(permutation, r);
    factor /= r;
  }
}

static void _rotate(ArrayInt permutation, int last) {
  int first = permutation[0];
  for (int i = 0; i < last; i++) permutation[i] = permutation[i + 1];
  permutation[last] = first;
}

static int _advance(ArrayInt permutation, ArrayInt counts, int n) {
  for (int r = 1; r < n; r++) {
    _rotate(permutation, r);
    int remaining = counts[r] - 1;
    counts[r] = remaining;
    if (remaining) return 1;
    counts[r] = r + 1;
  }
  return 0;
}

04 / 10

Mandelbrot bitmap

Test points in the complex plane and write a binary PBM bitmap.

Problem specification
Read and compare source
Read Mandelbrot bitmap source
Idiomatic x2c / main.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 *
 * Adapted from the contributions recorded in ../../benchmarks.json.
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <stdio.h>
#include <stdlib.h>

class Rows { int size, first, last; Array bytes; Thread worker; } *;

int main(int argc, char **argv) {
  int size = atoi(argv[1]);
  printf("P4\n%d %d\n", size, size);
  for (int first = 0; first < size; first += 96) auto {
    Array batches = [];
    for (int row = first; row < size && row < first + 96; row += 16)
      batches.push(Rows.new(size, row, row + 16 < size ? row + 16 : size));
    foreach (Rows rows in batches) {
      if (rows.worker) {
        rows.worker.join();
        rows.worker.free();
      }
      foreach (int byte in rows.bytes) putchar(byte);
    }
  }
  return 0;
}

static void Rows.init(Rows rows, int size, int first, int last) {
  rows.size = size;
  rows.first = first;
  rows.last = last;
  rows.bytes = [];
  int length = (last - first) * ((size + 7) / 8);
  for (int i = 0; i < length; i++) rows.bytes.push(0);
  if (size >= 256) rows.worker = Thread.start(_render, rows);
  else _render(rows);
}

static Var _render(Var input) {
  Rows rows = input;
  int offset = 0, size = rows.size;
  for (int y = rows.first; y < rows.last; y++) {
    for (int x = 0; x < size; x += 8) {
      int bits = size - x < 8 ? size - x : 8;
      unsigned byte = 0;
      for (int b = 0; b < bits; b++)
        byte = (byte << 1) | _inside(x + b, y, size);
      rows.bytes[offset++] = byte << (8 - bits);
    }
  }
  return void;
}

static unsigned _inside(int x, int y, int size) {
  double zr = 0.0, zi = 0.0, tr = 0.0, ti = 0.0;
  double cr = 2.0 * x / size - 1.5, ci = 2.0 * y / size - 1.0;
  for (int i = 0; i < 50 && tr + ti <= 4.0; i++) {
    zi = 2.0 * zr * zi + ci;
    zr = tr - ti + cr;
    tr = zr * zr;
    ti = zi * zi;
  }
  return tr + ti <= 4.0;
}
Tuned x2c / tuned.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 *
 * Adapted from the contributions recorded in ../../benchmarks.json.
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <stdio.h>
#include <stdlib.h>
#include "typed-array.x"

class Rows { int size, first, last; ArrayChar bytes; Thread worker; } *;

int main(int argc, char **argv) {
  int size = atoi(argv[1]);
  printf("P4\n%d %d\n", size, size);
  for (int first = 0; first < size; first += 96) auto {
    Array batches = [];
    for (int row = first; row < size && row < first + 96; row += 16)
      batches.push(Rows.new(size, row, row + 16 < size ? row + 16 : size));
    foreach (Rows rows in batches) {
      if (rows.worker) {
        rows.worker.join();
        rows.worker.free();
      }
      fwrite(rows.bytes.bytes, 1, rows.bytes.len(), stdout);
    }
  }
  return 0;
}

static void Rows.init(Rows rows, int size, int first, int last) {
  rows.size = size;
  rows.first = first;
  rows.last = last;
  rows.bytes = ArrayChar.new();
  int length = (last - first) * ((size + 7) / 8);
  for (int i = 0; i < length; i++) rows.bytes.push(0);
  if (size >= 256) rows.worker = Thread.start(_render, rows);
  else _render(rows);
}

static Var _render(Var input) {
  Rows rows = input;
  int offset = 0, size = rows.size;
  for (int y = rows.first; y < rows.last; y++) {
    for (int x = 0; x < size; x += 8) {
      int bits = size - x < 8 ? size - x : 8;
      unsigned byte = 0;
      for (int b = 0; b < bits; b++)
        byte = (byte << 1) | _inside(x + b, y, size);
      rows.bytes[offset++] = byte << (8 - bits);
    }
  }
  return void;
}

static unsigned _inside(int x, int y, int size) {
  double zr = 0.0, zi = 0.0, tr = 0.0, ti = 0.0;
  double cr = 2.0 * x / size - 1.5, ci = 2.0 * y / size - 1.0;
  for (int i = 0; i < 50 && tr + ti <= 4.0; i++) {
    zi = 2.0 * zr * zi + ci;
    zr = tr - ti + cr;
    tr = zr * zr;
    ti = zi * zi;
  }
  return tr + ti <= 4.0;
}

05 / 10

fasta

Generate repeated and random DNA sequences with the prescribed probability distributions.

Problem specification
Read and compare source
Read fasta source
Idiomatic x2c / main.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 * Algorithm and constants from Paul Hsieh's contributed C program.
 */

#include <stdlib.h>

static int seed = 42;
static String alu =
  "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG"
  "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA"
  "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT"
  "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA"
  "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG"
  "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC"
  "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";

class Choice { char letter; double cumulative; } *;

int main(int argc, char **argv) {
  int n = argc > 1 ? atoi(argv[1]) : 1000;
  puts(">ONE Homo sapiens alu");
  _repeat(2 * n);
  puts(">TWO IUB ambiguity codes");
  _random("acgtBDHKMNRSVWY", [
    0.27, 0.12, 0.12, 0.27, 0.02, 0.02, 0.02, 0.02,
    0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02], 3 * n);
  puts(">THREE Homo sapiens frequency");
  _random("acgt", [
    0.3029549426680, 0.1979883004921,
    0.1975473066391, 0.3015094502008], 5 * n);
  return 0;
}

static void _repeat(int count) {
  Buffer line = auto Buffer.new();
  for (int start = 0; start < count; start += 60) {
    line.clear();
    int end = start + 60 < count ? start + 60 : count;
    for (int i = start; i < end; i++)
      line.write_char(alu[i % alu.len()]);
    puts(line.str());
  }
}

static void _random(String letters, Array probabilities, int count) {
  Array choices = _choices(letters, probabilities);
  Buffer line = auto Buffer.new();
  for (int start = 0; start < count; start += 60) {
    line.clear();
    int end = start + 60 < count ? start + 60 : count;
    for (int i = start; i < end; i++) {
      seed = (seed * 3877 + 29573) % 139968;
      double random = (double) seed / 139968;
      int index = 0;
      Choice choice = choices[index];
      while (random >= choice.cumulative) choice = choices[++index];
      line.write_char(choice.letter);
    }
    puts(line.str());
  }
}

static Array _choices(String letters, Array probabilities) {
  Array choices = [];
  double cumulative = 0;
  for (int i = 0; i < probabilities.len(); i++) {
    cumulative += probabilities[i].double();
    choices.push(Choice.new(letters[i], cumulative));
  }
  return choices;
}

static void Choice.init(Choice choice, char letter, double cumulative) {
  choice.letter = letter;
  choice.cumulative = cumulative;
}
Tuned x2c / tuned.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 * Algorithm and constants from Paul Hsieh's contributed C program.
 */

#include <stdlib.h>
#include <string.h>
#include "typed-array.x"

static int seed = 42;
static String alu =
  "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG"
  "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA"
  "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT"
  "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA"
  "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG"
  "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC"
  "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";

int main(int argc, char **argv) {
  int n = argc > 1 ? atoi(argv[1]) : 1000;
  puts(">ONE Homo sapiens alu");
  _repeat(2 * n);
  puts(">TWO IUB ambiguity codes");
  _random("acgtBDHKMNRSVWY", _probabilities([
    0.27, 0.12, 0.12, 0.27, 0.02, 0.02, 0.02, 0.02,
    0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02]), 3 * n);
  puts(">THREE Homo sapiens frequency");
  _random("acgt", _probabilities([
    0.3029549426680, 0.1979883004921,
    0.1975473066391, 0.3015094502008]), 5 * n);
  return 0;
}

static void _repeat(int count) {
  char output[61 * 256];
  size_t used = 0, position = 0, length = alu.len();
  while (count > 0) {
    int line = count < 60 ? count : 60, remaining = line;
    while (remaining > 0) {
      size_t span = length - position;
      if (span > remaining) span = remaining;
      memcpy(output + used, (const char *) alu + position, span);
      used += span;
      remaining -= span;
      position += span;
      if (position == length) position = 0;
    }
    output[used++] = '\n';
    count -= line;
    if (used == sizeof(output)) {
      Stdout.write_all(output, used);
      used = 0;
    }
  }
  if (used) Stdout.write_all(output, used);
}

static void _random(String letters, ArrayDbl probabilities, int count) {
  double total = 0;
  int choices = probabilities.len();
  for (int i = 0; i < choices; i++) {
    total += probabilities[i];
    probabilities[i] = total;
  }
  char output[61 * 256];
  size_t used = 0;
  while (count > 0) {
    int line = count < 60 ? count : 60;
    for (int i = 0; i < line; i++) {
      seed = (seed * 3877 + 29573) % 139968;
      double random = (double) seed / 139968;
      int choice = 0;
      for (int j = 0; j < choices - 1; j++)
        choice += random >= probabilities[j];
      output[used++] = letters[choice];
    }
    output[used++] = '\n';
    count -= line;
    if (used == sizeof(output)) {
      Stdout.write_all(output, used);
      used = 0;
    }
  }
  if (used) Stdout.write_all(output, used);
}

static ArrayDbl _probabilities(Array values) {
  ArrayDbl result = ArrayDbl.new();
  foreach (double probability in values) result.push(probability);
  return result;
}

06 / 10

k-nucleotide

Count DNA fragments in growing maps and report frequencies and requested fragment counts.

Problem specification
Read and compare source
Read k-nucleotide source
Idiomatic x2c / main.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 */

class Batch { String sequence, key, output; int width; Thread worker; } *;

int main(void) {
  String sequence = _read();
  Array batches = [];
  foreach (String key in %("A" "AA" "GGT" "GGTA" "GGTATT"
    "GGTATTTTAATT" "GGTATTTTAATTTATAGT")) {
    Batch batch = Batch.new();
    batch.sequence = sequence;
    batch.key = key;
    batch.width = key.len();
    batch.worker = Thread.start(_run, batch);
    batches.push(batch);
  }
  foreach (Batch batch in batches) {
    batch.worker.join();
    batch.worker.free();
    printf("%s", batch.output);
  }
  return 0;
}

static Var _run(Var input) {
  Batch batch = input;
  Map counts = _count(batch.sequence, batch.width);
  Buffer output = auto Buffer.new();
  if (batch.width <= 2) {
    Array keys = [];
    foreach ((String key, Var count) in counts) keys.push(key);
    keys.sort_with(%!(String a, String b) => {
      int difference = counts[b].int() - counts[a].int();
      return difference ? difference : a.compare(b);
    });
    foreach (String key in keys)
      output.printf("%s %.3f\n", key,
        100.0 * counts[key].int() / (batch.sequence.len() - batch.width + 1));
    output.write("\n");
  }
  else output.printf("%d\t%s\n", counts.getdefault(batch.key, 0), batch.key);
  batch.output = output;
  return void;
}

static String _read(void) {
  Buffer sequence = auto Buffer.new();
  int found = 0;
  foreach (String line in Stdin) {
    if (!found) {
      if (line.startswith(">THREE")) found = 1;
    }
    else {
      if (line.startswith(">")) break;
      sequence.write(line.strip());
    }
  }
  return sequence.str().upper();
}

static Map _count(String sequence, int width) {
  Map counts = {};
  int last = sequence.len() - width;
  for (int i = 0; i <= last; i++) {
    String key = sequence[i:i + width];
    counts[key] = counts.getdefault(key, 0).int() + 1;
  }
  return counts;
}

static void Batch.init(Batch batch) {}
Tuned x2c / tuned.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 */

#include "substring-map.x"

class Batch { String sequence, key, output; int width; Thread worker; } *;

int main(void) {
  String sequence = _read();
  Array batches = [];
  foreach (String key in %("A" "AA" "GGT" "GGTA" "GGTATT"
    "GGTATTTTAATT" "GGTATTTTAATTTATAGT")) {
    Batch batch = Batch.new();
    batch.sequence = sequence;
    batch.key = key;
    batch.width = key.len();
    batch.worker = Thread.start(_run, batch);
    batches.push(batch);
  }
  foreach (Batch batch in batches) {
    batch.worker.join();
    batch.worker.free();
    printf("%s", batch.output);
  }
  return 0;
}

static Var _run(Var input) {
  Batch batch = input;
  MapSubInt counts = _count(batch.sequence, batch.width);
  Buffer output = auto Buffer.new();
  if (batch.width <= 2) {
    Map frequencies = counts.strings();
    Array keys = [];
    foreach ((String key, Var count) in frequencies) keys.push(key);
    keys.sort_with(%!(String a, String b) => {
      int difference = frequencies[b].int() - frequencies[a].int();
      return difference ? difference : a.compare(b);
    });
    foreach (String key in keys)
      output.printf("%s %.3f\n", key,
        100.0 * frequencies[key].int() / (batch.sequence.len() - batch.width + 1));
    output.write("\n");
  }
  else {
    Substr query = batch.key.substring(0, batch.width);
    output.printf("%d\t%s\n", _lookup(counts, query), batch.key);
  }
  batch.output = output;
  return void;
}

static String _read(void) {
  Buffer sequence = auto Buffer.new();
  int found = 0;
  foreach (String line in Stdin) {
    if (!found) {
      if (line.startswith(">THREE")) found = 1;
    }
    else {
      if (line.startswith(">")) break;
      sequence.write(line.strip());
    }
  }
  return sequence.str().upper();
}

static MapSubInt _count(String sequence, int width) {
  MapSubInt counts = MapSubInt.new();
  for (int i = 0; i + width <= sequence.len(); i++)
    counts.increment(sequence.substring(i, width));
  return counts;
}

/* MapSubInt exposes counts through iteration, without a lookup operation. */
static int _lookup(MapSubInt counts, Substr query) {
  unsigned cursor = 0;
  Substr key;
  int count;
  while (counts.try_next(cursor, key, count))
    if (key.equal(query)) return count;
  return 0;
}

static void Batch.init(Batch batch) {}

07 / 10

reverse-complement

Read FASTA records and write each sequence's reverse complement.

Problem specification
Read and compare source
Read reverse-complement source
Idiomatic x2c / main.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 */

int main(void) {
  Buffer sequence = auto Buffer.new();
  foreach (String line in Stdin) {
    if (line.startswith(">")) {
      _write(sequence);
      sequence.clear();
      Stdout.puts(line);
    }
    else {
      String text = line.strip();
      if (text) sequence.write(text);
    }
  }
  _write(sequence);
  return 0;
}

static void _write(Buffer sequence) {
  Buffer line = auto Buffer.new();
  for (ptrdiff_t end = sequence.len(); end > 0;) {
    line.clear();
    int count = end > 60 ? 60 : end;
    for (int i = 0; i < count; i++)
      line.write_char(_complement(sequence.get(--end)));
    puts(line.str());
  }
}

static int _complement(int ch) {
  if (ch >= 'a' && ch <= 'z') ch -= 'a' - 'A';
  switch (ch) {
    case 'A': return 'T';
    case 'C': return 'G';
    case 'G': return 'C';
    case 'T': case 'U': return 'A';
    case 'M': return 'K';
    case 'R': return 'Y';
    case 'W': return 'W';
    case 'S': return 'S';
    case 'Y': return 'R';
    case 'K': return 'M';
    case 'V': return 'B';
    case 'H': return 'D';
    case 'D': return 'H';
    case 'B': return 'V';
    case 'N': return 'N';
    default: return ch;
  }
}
Tuned x2c / tuned.xRepository source
/* The Computer Language Benchmarks Game
 * https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 */

#include "typed-array.x"
#include <string.h>
#include <errno.h>

int main(void) {
  ArrayChar sequence = ArrayChar.new();
  ArrayChar complements = ArrayChar.new();
  for (int i = 0; i < 128; i++) complements.push(i);
  String codes = "ACGTUMRWSYKVHDBN", pairs = "TGCAAKYWSRMBDHVN";
  for (int i = 0; i < codes.len(); i++) {
    complements[codes[i]] = pairs[i];
    complements[codes[i] + 'a' - 'A'] = pairs[i];
  }
  char input[16384];
  int line_start = 1, header = 0;
  size_t length;
  while ((length = fread(input, 1, sizeof(input), stdin)) > 0) {
    const char *cursor = input, *end = input + length;
    while (cursor < end) {
      if (line_start) {
        header = *cursor == '>';
        if (header) {
          _write(sequence, complements);
          sequence.clear();
        }
      }
      const char *newline = memchr(cursor, '\n', end - cursor);
      const char *next = newline ? newline + 1 : end;
      if (header) Stdout.write_all(cursor, next - cursor);
      else _append(sequence, cursor, (newline ? newline : end) - cursor);
      line_start = newline != NULL;
      cursor = next;
    }
  }
  if (ferror(stdin)) File.path_error(<read>, NULL, errno);
  _write(sequence, complements);
  return 0;
}

static void _append(ArrayChar sequence, const char *cursor, size_t length) {
  const char *end = cursor + length;
  while (cursor < end) {
    const char *cr = memchr(cursor, '\r', end - cursor);
    const char *next = cr ? cr : end;
    ((Block) sequence).append(cursor, next - cursor);
    cursor = cr ? cr + 1 : end;
  }
}

static void _write(ArrayChar sequence, ArrayChar complements) {
  for (ptrdiff_t i = 0, j = (ptrdiff_t) sequence.len() - 1; i <= j; i++, j--) {
    char first = complements[(unsigned char) sequence[i]];
    sequence[i] = complements[(unsigned char) sequence[j]];
    sequence[j] = first;
  }
  char output[61 * 256];
  size_t used = 0;
  for (size_t start = 0; start < sequence.len(); start += 60) {
    size_t count = sequence.len() - start;
    if (count > 60) count = 60;
    memcpy(output + used, (char *) sequence.bytes + start, count);
    used += count;
    output[used++] = '\n';
    if (used == sizeof(output)) {
      Stdout.write_all(output, used);
      used = 0;
    }
  }
  if (used) Stdout.write_all(output, used);
}

08 / 10

binary-trees

Allocate and check complete trees, including every leaf, at a range of depths.

Problem specification
Read and compare source
Read binary-trees source
Idiomatic x2c / main.xRepository source
/* The Computer Language Benchmarks Game: binary-trees.
   Every node is an ordinary heap class with two child fields. Leaves allocate the
   same Node as interior nodes. One ordinary Thread runs each depth batch;
   worker-local Scope regions use the runtime allocator. */

#include <stdio.h>
#include <stdlib.h>

class Node { Node left, right; } *;
class Batch { int depth; long iterations, check; Thread worker; } *;

int main(int argc, char **argv) {
  int maximum = argc > 1 ? atoi(argv[1]) : 10;
  if (maximum < 6) maximum = 6;
  auto {
    Node stretch = _tree(maximum + 1);
    printf("stretch tree of depth %d\t check: %ld\n",
      maximum + 1, stretch.check());
  }
  Node long_lived = _tree(maximum);
  Array batches = [];
  for (int depth = 4; depth <= maximum; depth += 2)
    batches.push(Batch.new(depth, maximum));
  foreach (Batch batch in batches) {
    batch.worker.join();
    batch.worker.free();
    printf("%ld\t trees of depth %d\t check: %ld\n",
      batch.iterations, batch.depth, batch.check);
  }
  printf("long lived tree of depth %d\t check: %ld\n",
    maximum, long_lived.check());
  return 0;
}

static void Batch.init(Batch batch, int depth, int maximum) {
  batch.depth = depth;
  batch.iterations = 1L << (maximum - depth + 4);
  batch.worker = Thread.start(_check_batch, batch);
}

static Var _check_batch(Var input) {
  Batch batch = input;
  long check = 0;
  for (long i = 0; i < batch.iterations; i++)
    auto { check += _tree(batch.depth).check(); }
  batch.check = check;
  return void;
}

static void Node.init(Node tree, Node left, Node right) {
  tree.left = left;
  tree.right = right;
}

static Node _tree(int depth) {
  if (!depth) return Node.new(NULL, NULL);
  return Node.new(_tree(depth - 1), _tree(depth - 1));
}

static long Node.check(Node tree) =>
  tree.left ? 1 + tree.left.check() + tree.right.check() : 1;
Tuned x2c / tuned.xRepository source
/* The Computer Language Benchmarks Game: binary-trees.
   Every node is an ordinary heap class with two child fields. Leaves allocate the
   same Node as interior nodes. One ordinary Thread runs each depth batch;
   worker-local Scope regions use the runtime allocator. */

#include <stdio.h>
#include <stdlib.h>

class Node { Node left, right; } *;
class Batch { int depth; long iterations, check; Thread worker; } *;

int main(int argc, char **argv) {
  int maximum = argc > 1 ? atoi(argv[1]) : 10;
  if (maximum < 6) maximum = 6;
  auto {
    Node stretch = _tree(maximum + 1);
    printf("stretch tree of depth %d\t check: %ld\n",
      maximum + 1, stretch.check());
  }
  Node long_lived = _tree(maximum);
  Array batches = [];
  for (int depth = 4; depth <= maximum; depth += 2)
    batches.push(Batch.new(depth, maximum));
  foreach (Batch batch in batches) {
    batch.worker.join();
    batch.worker.free();
    printf("%ld\t trees of depth %d\t check: %ld\n",
      batch.iterations, batch.depth, batch.check);
  }
  printf("long lived tree of depth %d\t check: %ld\n",
    maximum, long_lived.check());
  return 0;
}

static void Batch.init(Batch batch, int depth, int maximum) {
  batch.depth = depth;
  batch.iterations = 1L << (maximum - depth + 4);
  batch.worker = Thread.start(_check_batch, batch);
}

static Var _check_batch(Var input) {
  Batch batch = input;
  long check = 0;
  for (long i = 0; i < batch.iterations; i++)
    auto { check += _tree(batch.depth).check(); }
  batch.check = check;
  return void;
}

static void Node.init(Node tree, Node left, Node right) {
  tree.left = left;
  tree.right = right;
}

static Node _tree(int depth) {
  if (!depth) return Node.new(NULL, NULL);
  return Node.new(_tree(depth - 1), _tree(depth - 1));
}

static long Node.check(Node tree) =>
  tree.left ? 1 + tree.left.check() + tree.right.check() : 1;

09 / 10

regex-redux

Count regular-expression matches and apply an ordered chain of substitutions to DNA input.

Problem specification
Read and compare source
Read regex-redux source
Idiomatic x2c / main.xRepository source
/* The Computer Language Benchmarks Game: regex-redux.
   PCRE2's ordinary Regexp API performs the prescribed searches and ordered
   substitutions. Independent pattern counts use ordinary Threads. */

import "pcre2" with Regexp;
#include <stdio.h>

class Count { String pattern, sequence; ulong matches; Thread worker; } *;

int main(void) {
  String input = Stdin.string();
  Regexp strip = auto Regexp.compile(">.*\\n|\\n", 0);
  strip.jit_compile(PCRE2_JIT_COMPLETE);
  String sequence = strip.replace_all(input, "");
  Array counts = [];
  int parallel = sequence.len() >= 65536;
  foreach (String pattern in %(
    "agggtaaa|tttaccct"
    "[cgt]gggtaaa|tttaccc[acg]"
    "a[act]ggtaaa|tttacc[agt]t"
    "ag[act]gtaaa|tttac[agt]ct"
    "agg[act]taaa|ttta[agt]cct"
    "aggg[acg]aaa|ttt[cgt]ccct"
    "agggt[cgt]aa|tt[acg]accct"
    "agggta[cgt]a|t[acg]taccct"
    "agggtaa[cgt]|[acg]ttaccct"))
    counts.push(Count.new(pattern, sequence, parallel));
  String replaced = _substitute(sequence);
  foreach (Count count in counts) {
    if (count.worker) {
      count.worker.join();
      count.worker.free();
    }
    printf("%s %lu\n", count.pattern, count.matches);
  }
  printf("\n%lu\n%lu\n%lu\n",
    (ulong) input.len(), (ulong) sequence.len(), (ulong) replaced.len());
  return 0;
}

static void Count.init(Count count, String pattern, String sequence, int parallel) {
  count.pattern = pattern;
  count.sequence = sequence;
  if (parallel) count.worker = Thread.start(_count, count);
  else _count(count);
}

static Var _count(Var input) {
  Count count = input;
  Regexp regexp = auto Regexp.compile(count.pattern, 0);
  regexp.jit_compile(PCRE2_JIT_COMPLETE);
  count.matches = regexp.find_all(count.sequence).len();
  return void;
}

static String _substitute(String sequence) {
  String replaced = sequence;
  foreach (List substitution in %(
    ("tHa[Nt]" "<4>")
    ("aND|caN|Ha[DS]|WaS" "<3>")
    ("a[NSt]|BY" "<2>")
    ("<[^>]*>" "|")
    ("\\|[^|][^|]*\\|" "-"))) {
    String (pattern, replacement) = substitution;
    Regexp regexp = auto Regexp.compile(pattern, 0);
    regexp.jit_compile(PCRE2_JIT_COMPLETE);
    replaced = regexp.replace_all(replaced, replacement);
  }
  return replaced;
}
Tuned x2c / tuned.xRepository source
/* The Computer Language Benchmarks Game: regex-redux.
   Independent pattern counts use Threads, each with its own JIT-compiled
   Regexp and borrowed match-data block rather than capture Lists. */

import "pcre2" with Regexp;
#include "typed-array.x"
#include <stdio.h>

class Count { String pattern; ArrayChar sequence; ulong matches; Thread worker; } *;

int main(void) {
  String input = Stdin.string();
  ArrayChar sequence = ArrayChar.new();
  _replace(">.*\\n|\\n", input, input.len(), NULL, sequence);
  Array counts = [];
  int parallel = sequence.len() >= 65536;
  foreach (String pattern in %(
    "agggtaaa|tttaccct"
    "[cgt]gggtaaa|tttaccc[acg]"
    "a[act]ggtaaa|tttacc[agt]t"
    "ag[act]gtaaa|tttac[agt]ct"
    "agg[act]taaa|ttta[agt]cct"
    "aggg[acg]aaa|ttt[cgt]ccct"
    "agggt[cgt]aa|tt[acg]accct"
    "agggta[cgt]a|t[acg]taccct"
    "agggtaa[cgt]|[acg]ttaccct"))
    counts.push(Count.new(pattern, sequence, parallel));
  size_t replaced = _substitute(sequence);
  foreach (Count count in counts) {
    if (count.worker) {
      count.worker.join();
      count.worker.free();
    }
    printf("%s %lu\n", count.pattern, count.matches);
  }
  printf("\n%lu\n%lu\n%lu\n",
    (ulong) input.len(), (ulong) sequence.len(), (ulong) replaced);
  return 0;
}

static void Count.init(Count count, String pattern, ArrayChar sequence, int parallel) {
  count.pattern = pattern;
  count.sequence = sequence;
  if (parallel) count.worker = Thread.start(_count, count);
  else _count(count);
}

static Var _count(Var input) {
  Count count = input;
  Regexp regexp = auto Regexp.compile(count.pattern, 0);
  regexp.jit_compile(PCRE2_JIT_COMPLETE);
  pcre2_match_data *data = regexp.native_match_data();
  PCRE2_SIZE *bounds = pcre2_get_ovector_pointer(data);
  pcre2_code *code = regexp.native();
  pcre2_match_context *context = regexp.native_match_context();
  ulong matches = 0, offset = 0;
  const char *bytes = count.sequence.bytes ? count.sequence.bytes : "";
  size_t length = count.sequence.len();
  while (pcre2_jit_match(code, (PCRE2_SPTR) bytes,
      length, offset, 0, data, context) >= 0) {
    matches++;
    offset = bounds[1];
  }
  count.matches = matches;
  return void;
}

static size_t _substitute(ArrayChar sequence) {
  ArrayChar first = auto ArrayChar.new(), second = auto ArrayChar.new();
  ArrayChar current = sequence, next = first;
  foreach (List substitution in %(
    ("tHa[Nt]" "<4>")
    ("aND|caN|Ha[DS]|WaS" "<3>")
    ("a[NSt]|BY" "<2>")
    ("<[^>]*>" "|")
    ("\\|[^|][^|]*\\|" "-"))) {
    String (pattern, replacement) = substitution;
    _replace(pattern, current.bytes, current.len(), replacement, next);
    current = next;
    next = next == first ? second : first;
  }
  return current.len();
}

/* All six prescribed patterns consume at least one byte; replacements are
   literal text. Scratch buffers alternate instead of interning each pass. */
static void _replace(
  String pattern, const char *source, size_t length, String replacement,
  ArrayChar output) {
  Regexp regexp = auto Regexp.compile(pattern, 0);
  regexp.jit_compile(PCRE2_JIT_COMPLETE);
  pcre2_match_data *data = regexp.native_match_data();
  PCRE2_SIZE *bounds = pcre2_get_ovector_pointer(data);
  pcre2_code *code = regexp.native();
  pcre2_match_context *context = regexp.native_match_context();
  const char *bytes = source ? source : "";
  size_t offset = 0, size = replacement.len();
  output.clear();
  int result;
  while ((result = pcre2_jit_match(code, (PCRE2_SPTR) bytes, length,
      offset, 0, data, context)) >= 0) {
    ((Block) output).append(bytes + offset, bounds[0] - offset);
    ((Block) output).append(replacement, size);
    offset = bounds[1];
  }
  if (result != PCRE2_ERROR_NOMATCH)
    raise %(bad-state (library "PCRE2") (operation "replace") (code $result));
  ((Block) output).append(bytes + offset, length - offset);
}

10 / 10

pidigits

Generate decimal digits of pi with the prescribed arbitrary-precision spigot algorithm.

Problem specification
Read and compare source
Read pidigits source
Idiomatic x2c / main.xRepository source
/* The Computer Language Benchmarks Game: pidigits.
   GMP supplies arbitrary precision. The spigot performs both extract(3) and
   extract(4), as required, through its own mutable GMP values. */

#include <gmp.h>
#include "cleanup.x"
#include <stdio.h>
#include <stdlib.h>

typedef struct Spigot {
  mpz_t numerator, accumulator, denominator, term, digit;
} Spigot;

$cleanup.by(Spigot, drop);

int main(int argc, char **argv) {
  int count = argc > 1 ? atoi(argv[1]) : 30, emitted = 0;
  auto Spigot spigot = Spigot.new();
  for (ulong k = 1; emitted < count; k++) {
    spigot.advance(k);
    if (mpz_cmp(spigot.numerator, spigot.accumulator) > 0) continue;
    ulong digit = spigot.extract(3);
    if (digit != spigot.extract(4)) continue;
    putchar('0' + digit);
    if (++emitted % 10 == 0) printf("\t:%d\n", emitted);
    spigot.eliminate(digit);
  }
  if (emitted % 10) {
    for (int i = emitted % 10; i < 10; i++) putchar(' ');
    printf("\t:%d\n", emitted);
  }
  return 0;
}

static Spigot Spigot.new(void) {
  Spigot state;
  mpz_init_set_ui(state.numerator, 1);
  mpz_init_set_ui(state.accumulator, 0);
  mpz_init_set_ui(state.denominator, 1);
  mpz_init_set_ui(state.term, 0);
  mpz_init_set_ui(state.digit, 0);
  return state;
}

static void Spigot.drop(Spigot &state) {
  mpz_clear(state.numerator);
  mpz_clear(state.accumulator);
  mpz_clear(state.denominator);
  mpz_clear(state.term);
  mpz_clear(state.digit);
}

static void Spigot.advance(Spigot &state, ulong k) {
  mpz_mul_ui(state.term, state.numerator, 2);
  mpz_add(state.accumulator, state.accumulator, state.term);
  mpz_mul_ui(state.accumulator, state.accumulator, 2 * k + 1);
  mpz_mul_ui(state.denominator, state.denominator, 2 * k + 1);
  mpz_mul_ui(state.numerator, state.numerator, k);
}

static ulong Spigot.extract(Spigot &state, ulong nth) {
  mpz_mul_ui(state.term, state.numerator, nth);
  mpz_add(state.term, state.term, state.accumulator);
  mpz_tdiv_q(state.digit, state.term, state.denominator);
  return mpz_get_ui(state.digit);
}

static void Spigot.eliminate(Spigot &state, ulong digit) {
  mpz_mul_ui(state.term, state.denominator, digit);
  mpz_sub(state.accumulator, state.accumulator, state.term);
  mpz_mul_ui(state.accumulator, state.accumulator, 10);
  mpz_mul_ui(state.numerator, state.numerator, 10);
}
Tuned x2c / tuned.xRepository source
/* The Computer Language Benchmarks Game: pidigits.
   GMP supplies arbitrary precision. Fused multiply-add and multiply-subtract
   operations save intermediate products; both required extracts remain. */

#include <gmp.h>
#include "cleanup.x"
#include <stdio.h>
#include <stdlib.h>

typedef struct Spigot {
  mpz_t numerator, accumulator, denominator, term, digit;
} Spigot;

$cleanup.by(Spigot, drop);

int main(int argc, char **argv) {
  int count = argc > 1 ? atoi(argv[1]) : 30, emitted = 0;
  auto Spigot spigot = Spigot.new();
  for (ulong k = 1; emitted < count; k++) {
    spigot.advance(k);
    if (mpz_cmp(spigot.numerator, spigot.accumulator) > 0) continue;
    ulong digit = spigot.extract(3);
    if (digit != spigot.extract(4)) continue;
    putchar('0' + digit);
    if (++emitted % 10 == 0) printf("\t:%d\n", emitted);
    spigot.eliminate(digit);
  }
  if (emitted % 10) {
    for (int i = emitted % 10; i < 10; i++) putchar(' ');
    printf("\t:%d\n", emitted);
  }
  return 0;
}

static Spigot Spigot.new(void) {
  Spigot state;
  mpz_init_set_ui(state.numerator, 1);
  mpz_init_set_ui(state.accumulator, 0);
  mpz_init_set_ui(state.denominator, 1);
  mpz_init_set_ui(state.term, 0);
  mpz_init_set_ui(state.digit, 0);
  return state;
}

static void Spigot.drop(Spigot &state) {
  mpz_clear(state.numerator);
  mpz_clear(state.accumulator);
  mpz_clear(state.denominator);
  mpz_clear(state.term);
  mpz_clear(state.digit);
}

static void Spigot.advance(Spigot &state, ulong k) {
  mpz_addmul_ui(state.accumulator, state.numerator, 2);
  mpz_mul_ui(state.accumulator, state.accumulator, 2 * k + 1);
  mpz_mul_ui(state.denominator, state.denominator, 2 * k + 1);
  mpz_mul_ui(state.numerator, state.numerator, k);
}

static ulong Spigot.extract(Spigot &state, ulong nth) {
  mpz_mul_ui(state.term, state.numerator, nth);
  mpz_add(state.term, state.term, state.accumulator);
  mpz_tdiv_q(state.digit, state.term, state.denominator);
  return mpz_get_ui(state.digit);
}

static void Spigot.eliminate(Spigot &state, ulong digit) {
  mpz_submul_ui(state.accumulator, state.denominator, digit);
  mpz_mul_ui(state.accumulator, state.accumulator, 10);
  mpz_mul_ui(state.numerator, state.numerator, 10);
}

Run the suite

Check the programs locally.

From a repository checkout with the compiler built, run all official fixtures and quick-profile comparisons, or select individual problems.

make shoot-check

# Check two selected problems.
python3 examples/shootout/tools/shootout.py check --profile quick \
  --only mandelbrot --only binarytrees

The full reference suite needs the language toolchains, PCRE2, and GMP. The suite guide lists dependencies, build options, input sizes, and measurement methods.