Skip to content

chore: add bson-ext to benchmark tool #503

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions etc/benchmarks/lib_runner.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/no-var-requires */
import { performance } from 'perf_hooks';
import { readFile } from 'fs/promises';
import { cpus, totalmem } from 'os';
import { exec as execCb } from 'child_process';
import { promisify } from 'util';
const exec = promisify(execCb);

const hw = cpus();
const ram = totalmem() / 1024 ** 3;
const platform = { name: hw[0].model, cores: hw.length, ram: `${ram}GB` };

export const systemInfo = iterations =>
[
`\n- cpu: ${platform.name}`,
`- cores: ${platform.cores}`,
`- os: ${process.platform}`,
`- ram: ${platform.ram}`,
`- iterations: ${iterations.toLocaleString()}`
].join('\n');

export const readJSONFile = async path =>
JSON.parse(await readFile(new URL(path, import.meta.url), { encoding: 'utf8' }));

function average(array) {
let sum = 0;
for (const value of array) sum += value;
return sum / array.length;
}

function testPerformance(lib, [fn, arg], iterations) {
let measurements = [];
let thrownError = null;
for (let i = 0; i < iterations; i++) {
const start = performance.now();
try {
fn(i, lib, arg);
} catch (error) {
thrownError = error;
break;
}
const end = performance.now();
measurements.push(end - start);
}
return { result: average(measurements).toFixed(8), thrownError };
}

export function getCurrentLocalBSON(libs) {
return libs.filter(({ name }) => name === 'local')[0];
}

export async function getLibs() {
return await Promise.all([
(async () => {
const { stdout } = await exec('git rev-parse --short HEAD');
const hash = stdout.trim();
return {
name: 'local',
lib: await import('../../lib/bson.js'),
version: hash
};
})(),
(async () => ({
name: 'released',
lib: await import('../../node_modules/bson_latest/lib/bson.js'),
version: (await readJSONFile('../../node_modules/bson_latest/package.json')).version
}))(),
(async () => {
const legacyBSON = (await import('../../node_modules/bson_legacy/index.js')).default;
return {
name: 'previous major',
lib: { ...legacyBSON, ...legacyBSON.prototype },
version: (await readJSONFile('../../node_modules/bson_legacy/package.json')).version
};
})(),
(async () => ({
name: 'bson-ext',
lib: await import('../../node_modules/bson_ext/lib/index.js'),
version: (await readJSONFile('../../node_modules/bson_ext/package.json')).version
}))()
]).catch(error => {
console.error(error);
console.error(
`Please run:\n${[
'npm run build',
'npm install --no-save bson_ext@npm:bson-ext@4 bson_legacy@npm:bson@1 bson_latest@npm:bson@latest'
].join('\n')}`
);
process.exit(1);
});
}

/**
* ```ts
* interface {
* iterations?: number;
* setup: (lib: any[]) => any;
* name: string;
* run:(index: number, bson: typeof import('../../src/bson'), setupRes: any) => any )
* }
* ```
*/
export async function runner({ iterations, setup, name, run, skip }) {
if (skip) {
console.log(`skipped ${name}\n`);
return;
}
const BSONLibs = await getLibs();
const setupResult = setup?.(BSONLibs) ?? null;

console.log(`\ntesting: ${name}`);

for (const bson of BSONLibs) {
const { result: perf, thrownError } = testPerformance(bson, [run, setupResult], iterations);
if (thrownError != null) {
console.log(
`${bson.name.padEnd(14, ' ')} - v ${bson.version.padEnd(8, ' ')} - error ${thrownError}`
);
} else {
console.log(
`${bson.name.padEnd(14, ' ')} - v ${bson.version.padEnd(8, ' ')} - avg ${perf}ms`
);
}
}

console.log();
}
147 changes: 59 additions & 88 deletions etc/benchmarks/main.mjs
Original file line number Diff line number Diff line change
@@ -1,95 +1,66 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import { performance } from 'perf_hooks';
import { readFile } from 'fs/promises';
import { cpus, totalmem } from 'os';
import { runner, systemInfo, getCurrentLocalBSON } from './lib_runner.mjs';

const hw = cpus();
const ram = totalmem() / 1024 ** 3;
const platform = { name: hw[0].model, cores: hw.length, ram: `${ram}GB` };
const ITERATIONS = 1_000_000;
const iterations = 1_000_000;
const startedEntireRun = performance.now();
console.log(systemInfo(iterations));
console.log();

const systemInfo = [
`\n- cpu: ${platform.name}`,
`- cores: ${platform.cores}`,
`- os: ${process.platform}`,
`- ram: ${platform.ram}`,
`- iterations: ${ITERATIONS.toLocaleString()}`
].join('\n');

const readJSONFile = async path =>
JSON.parse(await readFile(new URL(path, import.meta.url), { encoding: 'utf8' }));

function average(array) {
let sum = 0;
for (const value of array) sum += value;
return sum / array.length;
}

function testPerformance(fn, iterations = ITERATIONS) {
let measurements = [];
for (let i = 0; i < iterations; i++) {
const start = performance.now();
fn(i);
const end = performance.now();
measurements.push(end - start);
}
return average(measurements).toFixed(8);
}

async function main() {
const [currentBSON, currentReleaseBSON, legacyBSONLib] = await Promise.all([
(async () => ({
lib: await import('../../lib/bson.js'),
version: 'current local'
}))(),
(async () => ({
lib: await import('../../node_modules/bson_latest/lib/bson.js'),
version: (await readJSONFile('../../node_modules/bson_latest/package.json')).version
}))(),
(async () => {
const legacyBSON = (await import('../../node_modules/bson_legacy/index.js')).default;
return {
lib: { ...legacyBSON, ...legacyBSON.prototype },
version: (await readJSONFile('../../node_modules/bson_legacy/package.json')).version
};
})()
]).catch(error => {
console.error(error);
console.error(
`Please run:\n${[
'npm run build',
'npm install --no-save bson_legacy@npm:bson@1 bson_latest@npm:bson@latest'
].join('\n')}`
);
process.exit(1);
});

const documents = Array.from({ length: ITERATIONS }, () =>
currentReleaseBSON.lib.serialize({
_id: new currentReleaseBSON.lib.ObjectId(),
field1: 'value1'
})
);

console.log(systemInfo);

for (const bson of [currentBSON, currentReleaseBSON, legacyBSONLib]) {
console.log(`\nBSON@${bson.version}`);
console.log(
`deserialize({ oid, string }, { validation: { utf8: false } }) takes ${testPerformance(i =>
bson.lib.deserialize(documents[i], { validation: { utf8: false } })
)}ms on average`
);

const oidBuffer = Buffer.from('00'.repeat(12), 'hex');
console.log(
`new Oid(buf) take ${testPerformance(() => new bson.lib.ObjectId(oidBuffer))}ms on average`
////////////////////////////////////////////////////////////////////////////////////////////////////
await runner({
skip: false,
name: 'deserialize({ oid, string }, { validation: { utf8: false } })',
iterations,
setup(libs) {
const bson = getCurrentLocalBSON(libs);
return Array.from({ length: iterations }, () =>
bson.lib.serialize({
_id: new bson.lib.ObjectId(),
field1: 'value1'
})
);
},
run(i, bson, documents) {
bson.lib.deserialize(documents[i], { validation: { utf8: false } });
}
});
////////////////////////////////////////////////////////////////////////////////////////////////////
await runner({
skip: true,
name: 'new Oid(buf)',
iterations,
setup() {
return Buffer.from('00'.repeat(12), 'hex');
},
run(i, bson, oidBuffer) {
new bson.lib.ObjectId(oidBuffer);
}
});
////////////////////////////////////////////////////////////////////////////////////////////////////
await runner({
skip: true,
name: 'BSON.deserialize(largeDocument)',
iterations,
setup(libs) {
const bson = getCurrentLocalBSON(libs);
const entries = Array.from({ length: 10 }, (_, i) => [
`${i}_${'a'.repeat(10)}`,
'b'.repeat(10)
]);
const document = Object.fromEntries(entries);
const bytes = bson.lib.serialize(document);
console.log(`largeDocument { byteLength: ${bytes.byteLength} }`);
return bytes;
},
run(i, bson, largeDocument) {
new bson.lib.deserialize(largeDocument);
}
});

console.log();
}

main()
.then(() => null)
.catch(error => console.error(error));
// End
console.log(
'Total time taken to benchmark:',
(performance.now() - startedEntireRun).toLocaleString(),
'ms'
);