62 lines
2.4 KiB
JavaScript
62 lines
2.4 KiB
JavaScript
const assert = require('node:assert/strict');
|
|
const { readFileSync } = require('node:fs');
|
|
const { resolve } = require('node:path');
|
|
const { gzipSync } = require('node:zlib');
|
|
|
|
const [directory, wasmExec] = process.argv.slice(2);
|
|
require(wasmExec);
|
|
|
|
function load(file, imports) {
|
|
const bytes = readFileSync(resolve(directory, file));
|
|
const module = new WebAssembly.Module(bytes);
|
|
console.log(file, bytes.length, 'bytes, gzip', gzipSync(bytes).length, 'bytes');
|
|
return new WebAssembly.Instance(module, imports);
|
|
}
|
|
|
|
function measure(fn, args, count, values) {
|
|
let sum = 0;
|
|
const start = performance.now();
|
|
for (let i = 0; i < count; i++) sum += Number(fn(args[i & 1]));
|
|
const elapsed = performance.now() - start;
|
|
assert.equal(sum, Math.ceil(count / 2) * values[0] + Math.floor(count / 2) * values[1]);
|
|
return elapsed * 1e6 / count;
|
|
}
|
|
|
|
const go = new Go();
|
|
const goInstance = load('go.wasm', go.importObject);
|
|
go.run(goInstance).catch(error => {
|
|
console.error(error);
|
|
process.exitCode = 1;
|
|
});
|
|
const rust = load('rust.wasm', {}).exports;
|
|
const goDirect = goInstance.exports;
|
|
const goCallback = {
|
|
recursive: globalThis.goRecursive,
|
|
iterative: globalThis.goIterative,
|
|
identity: globalThis.goIdentity,
|
|
};
|
|
|
|
console.log(process.version, process.platform, process.arch);
|
|
console.log('case n Rust-direct-ns Go-direct-ns Go-callback-ns');
|
|
for (const kind of ['identity', 'iterative', 'recursive']) {
|
|
const inputs = kind === 'identity' ? [[40, 40]] : [[30, 832040], [35, 9227465], [40, 102334155]];
|
|
const counts = kind === 'recursive' ? [1, 1, 1] : [200000, 200000, 2000];
|
|
for (const [n, expected] of inputs) {
|
|
const functions = [rust[kind], goDirect[kind], goCallback[kind]];
|
|
const directArgs = [BigInt(n), BigInt(n - 1)];
|
|
const args = [directArgs, directArgs, [n, n - 1]];
|
|
const previous = kind === 'identity' ? n - 1 : { 30: 514229, 35: 5702887, 40: 63245986 }[n];
|
|
const values = [expected, previous];
|
|
const samples = functions.map(() => []);
|
|
functions.forEach((fn, index) => measure(fn, args[index], Math.min(counts[index], 1000), values));
|
|
for (let trial = 0; trial < 7; trial++) {
|
|
for (let offset = 0; offset < functions.length; offset++) {
|
|
const index = (trial + offset) % functions.length;
|
|
samples[index].push(measure(functions[index], args[index], counts[index], values));
|
|
}
|
|
}
|
|
const medians = samples.map(values => values.sort((a, b) => a - b)[3].toFixed(2));
|
|
console.log(kind, n, ...medians);
|
|
}
|
|
}
|