> For the complete documentation index, see [llms.txt](https://openjs.wiki.gd/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://openjs.wiki.gd/example-scripts/benchmarker.md).

# Benchmarker

Allows you to measure the compute performance of OpenJS on your machine.\
To run the benchmark, **run the command `/benchmark` in the console.** Example result:

<figure><img src="https://2747847701-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHqXqB9FayGrV9U31bfmT%2Fuploads%2FHcMdA6lvemlAnDXdZhCE%2Fimage.png?alt=media&amp;token=44f97a6f-3f3f-4423-a299-dc1a7578f451" alt=""><figcaption></figcaption></figure>

{% code title="Benchmark.js" %}

```js
// ════════════════════════════════════════════════════════════════
//  OpenJS Benchmark  —  drop into scripts/ and run /oj load benchmark.js
// ════════════════════════════════════════════════════════════════

var System         = Java.type("java.lang.System");
var CountDownLatch = Java.type("java.util.concurrent.CountDownLatch");
var TimeUnit       = Java.type("java.util.concurrent.TimeUnit");
var prewarms       = 30;
var warmupPause    = 3;
var baselinePCT    = 700000

var TARGETS = {
    jsCompute:   5000000,
    jsonOps:     200000,
    ImportClass: 700,
    sharedVars:  15000,
    mainThread:  300,
    asyncSpawn:  1000,
};

// Score is scaled so that hitting 100% target = 500 pts,
// double target = 1000 pts, half = 250 pts — always in the hundreds.
var SCORE_SCALE = 500;

var BAR_WIDTH   = 24;
var LABEL_WIDTH = 14;

var GREEN  = "\u001B[38;5;49m";
var YELLOW = "\u001B[38;5;220m";
var RED    = "\u001B[38;5;203m";
var CYAN   = "\u001B[38;5;81m";
var GRAY   = "\u001B[38;5;240m";
var BOLD   = "\u001B[1m";
var RESET  = "\u001B[0m";

function scoreColor(pct) {
    return pct >= 80 ? GREEN : pct >= 50 ? YELLOW : RED;
}

function makeBar(pct, width) {
    width = width || BAR_WIDTH;
    var filled = Math.round(Math.min(100, pct) / 100 * width);
    var c = scoreColor(pct);
    return c + "#".repeat(filled) + GRAY + "=".repeat(width - filled) + RESET;
}

function padR(s, n) { s = String(s); while (s.length < n) s += " "; return s; }
function padL(s, n) { s = String(s); while (s.length < n) s = " " + s; return s; }

function fmtOps(n) {
    if (n >= 1000000) return padL((n / 1000000).toFixed(2) + "M", 8);
    if (n >= 1000)    return padL((n / 1000).toFixed(2)    + "K", 8);
    return padL(String(n), 8);
}

function calcPct(ops, target)   { return Math.min(100, Math.round(ops / target * 100)); }
function calcScore(ops, target) { return Math.round(ops / target * SCORE_SCALE); }

function printRow(label, pct, opsStr, score) {
    var c = scoreColor(pct);
    var scoreStr = CYAN + padL(String(score), 5) + " pts" + RESET;
    log.info(
        "  " + CYAN  + padR(label, LABEL_WIDTH) + RESET +
        "  " + c + BOLD + padL(pct + "%", 5) + RESET +
        "  " + makeBar(pct) +
        "  " + GRAY + opsStr + "/s" + RESET +
        "  " + scoreStr
    );
}

function printSep() {
    log.info(GRAY + "  " + "─".repeat(72) + RESET);
}

function timedLoop(fn, iterations) {
    var t0 = System.nanoTime();
    for (var i = 0; i < iterations; i++) fn(i);
    var ms = (System.nanoTime() - t0) / 1e6;
    return { ms: ms, ops: Math.floor(iterations / (ms / 1000)) };
}

// ── Benchmark functions ────────────────────────────────────────

function bJsCompute() {
    return timedLoop(function(i) {
        var x = i * 3.14159265 + i / 2.71828182;
        x = Math.sqrt(Math.abs(x)) + Math.log(i + 1);
        x = (x % 999) * 1.0001;
    }, 1000000);
}

function bJsonOps() {
    var obj = { id: 0, name: "openjs-bench", values: [1, 2, 3, 4, 5], active: true, nested: { x: 99 } };
    return timedLoop(function(i) {
        obj.id = i;
        JSON.parse(JSON.stringify(obj));
    }, 10000);
}

function bImportClass() {
    return timedLoop(function(i) {
        importClass("org.bukkit.Bukkit")
    }, 5);
}

function bSharedVars() {
    setShared("__bmark_sv", 0);
    return timedLoop(function(i) {
        setShared("__bmark_sv", i);
        getShared("__bmark_sv");
    }, 2000);
}

function bMainThread() {
    var N = 200;
    var latch = new CountDownLatch(N);
    var t0 = System.nanoTime();
    for (var i = 0; i < N; i++) {
        task.main(function() { latch.countDown(); });
    }
    var timedOut = !latch.await(15, TimeUnit.SECONDS);
    var ms = (System.nanoTime() - t0) / 1e6;
    if (timedOut) log.warn("  [WARN] Main-thread benchmark timed out");
    return { ms: ms, ops: Math.floor(N / (ms / 1000)) };
}

function bAsyncSpawn() {
    var N = 100;
    var latch = new CountDownLatch(N);
    var t0 = System.nanoTime();
    for (var i = 0; i < N; i++) {
        task.spawn(function() { latch.countDown(); });
    }
    var timedOut = !latch.await(15, TimeUnit.SECONDS);
    var ms = (System.nanoTime() - t0) / 1e6;
    if (timedOut) log.warn("  [WARN] Async-spawn benchmark timed out");
    return { ms: ms, ops: Math.floor(N / (ms / 1000)) };
}

var benchFns = [
    { key: "jsCompute",  fn: bJsCompute  },
    { key: "jsonOps",    fn: bJsonOps    },
    { key: "ImportClass",fn: bImportClass},
    { key: "sharedVars", fn: bSharedVars },
    { key: "mainThread", fn: bMainThread },
    { key: "asyncSpawn", fn: bAsyncSpawn },
];

function calculatePCT(score) {
    return Math.round(score/baselinePCT*100)
}

// ── Prewarm with live progress bar ────────────────────────────
function preWarmBenchmark() {
    var PREWARM_BAR = 32;
    var reportEvery = Math.max(1, Math.floor(prewarms / 20)); // update ~20 times
    var lastResults = null;
    var t0 = System.nanoTime();

    log.info("");
    log.info(CYAN + BOLD + "  Warming up JIT  (" + prewarms + " passes)..." + RESET);
    log.info("");

    for (var i = 0; i < prewarms; i++) {
        var results = {};
        for (var b = 0; b < benchFns.length; b++) {
            var r = benchFns[b].fn();
            results[benchFns[b].key] = r;
        }
        lastResults = results;

        // Print progress bar every reportEvery iterations
        if ((i + 1) % reportEvery === 0 || i === prewarms - 1) {
            var pct = Math.round((i + 1) / prewarms * 100);
            var filled = Math.round(pct / 100 * PREWARM_BAR);
            var bar = YELLOW + "#".repeat(filled) + GRAY + "=".repeat(PREWARM_BAR - filled) + RESET;
            log.info(
                "  " + GRAY + "Prewarm  " + RESET +
                YELLOW + BOLD + padL(pct + "%", 4) + RESET +
                "  [" + bar + "]  " +
                GRAY + (i + 1) + "/" + prewarms + RESET
            );
        }
    }

    var warmMs = (System.nanoTime() - t0) / 1e6;

    // Compute prewarm score from last pass
    var pctSum = 0;
    var scoreSum = 0;
    for (var b = 0; b < benchFns.length; b++) {
        var key = benchFns[b].key;
        var ops = lastResults[key].ops;
        pctSum   += calcPct(ops, TARGETS[key]);
        scoreSum += calcScore(ops, TARGETS[key]);
    }
    var avgPct   = Math.round(pctSum / benchFns.length);
    var totalScore = scoreSum;
    var warmSec  = (warmMs / 1000).toFixed(2);

    var pc = scoreColor(avgPct);
    log.info("");
    log.info(
        "  " + BOLD + CYAN + "Prewarm complete" + RESET +
        "  " + pc + BOLD + avgPct + "%" + RESET +
        "  score: " + CYAN + BOLD + totalScore + " pts" + RESET +
        "  " + GRAY + "(" + warmSec + "s)" + RESET
    );
    log.info("");
    System.gc();
    task.wait(warmupPause);
}

function mainBench() {
    // ── Main runner ────────────────────────────────────────────────
    task.spawn(function() {
        preWarmBenchmark();

        var tests = [
            { key: "jsCompute",  label: "JS Compute",   fn: bJsCompute  },
            { key: "jsonOps",    label: "JSON Ops",     fn: bJsonOps    },
            { key: "sharedVars", label: "Shared Vars",  fn: bSharedVars },
            { key: "ImportClass",label: "Class lookup", fn: bImportClass},
            { key: "mainThread", label: "Main Thread",  fn: bMainThread },
            { key: "asyncSpawn", label: "Async Spawn",  fn: bAsyncSpawn },
        ];

        log.info(CYAN + BOLD + "  ╔══════════════════════════════════════════════╗" + RESET);
        log.info(CYAN + BOLD + "  ║               OpenJS Benchmark               ║" + RESET);
        log.info(CYAN + BOLD + "  ║   Plugin Version: " + RESET + GREEN + padR(plugin.getDescription().getVersion().toString().substring(0, 24), 27) + CYAN + BOLD + "║" + RESET);
        log.info(CYAN + BOLD + "  ║   " + RESET + GRAY + padR(new java.util.Date().toString().substring(0, 24), 43) + CYAN + BOLD + "║" + RESET);
        log.info(CYAN + BOLD + "  ╚══════════════════════════════════════════════╝" + RESET);
        log.info("");
        log.info(GRAY + "  " + padR("Category", LABEL_WIDTH) + "  Score  " + padR("Bar", BAR_WIDTH + 2) + "  Throughput     Points" + RESET);
        printSep();

        var pctScores   = [];
        var totalPoints = 0;

        for (var i = 0; i < tests.length; i++) {
            var t = tests[i];
            try {
                var r    = t.fn();
                var pct  = calcPct(r.ops, TARGETS[t.key]);
                var pts  = calcScore(r.ops, TARGETS[t.key]);
                pctScores.push(pct);
                totalPoints += pts;
                printRow(t.label, pct, fmtOps(r.ops), pts);
            } catch(e) {
                pctScores.push(0);
                log.error("  [FAIL] " + t.label + " threw: " + e);
            }
        }

        var overallPct = calculatePCT(totalPoints);
        var oColor     = scoreColor(overallPct);
        var maxPoints  = benchFns.length * SCORE_SCALE; // perfect score baseline

        log.info("");
        printSep();
        log.info(
            "  " + BOLD + padR("Overall", LABEL_WIDTH) + RESET +
            "  " + oColor + BOLD + padL(overallPct + "%", 5) + RESET +
            "  " + makeBar(overallPct) +
            "  " + GRAY + "  avg pct " + RESET +
            "  " + CYAN + BOLD + padL(String(totalPoints), 5) + " pts" + RESET
        );
        printSep();
        log.info("");

        try { DiskApi.saveFile("__bmark", false, false); } catch(e) {}
    });
}

addCommand("benchmark", {
    onCommand: function (sender) {
        if (!sender.getLocation) {
            mainBench()
        }
    }
});
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://openjs.wiki.gd/example-scripts/benchmarker.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
