Published
Edited
Jan 14, 2022
Importers
1 star
Insert cell
Insert cell
function sqrt(b) {
b.tic(); // start timing

for (let i = 0; i < b.iterations; i++) {
const sum = Math.sqrt(i);
}

b.toc(); // end timing

b.end(); // finish the benchmark
}
Insert cell
benchTable('Math.sqrt', sqrt)
Insert cell
Insert cell
function bench(...args) {
function executor(resolve, reject) {
let results = [];

// Create a new benchmark harness:
const h = stdlib.harness.createHarness(onFinish);

// Create a stream for benchmark results:
const stream = h.createStream({ objectMode: true });

// Listen for 'data' events (i.e., benchmark results):
stream.on("data", onResults);

// Run the provided benchmark(s):
h.apply(h, args);

function onResults(data) {
results.push(data);
}

function onFinish() {
// Once a benchmark finishes, close the harness:
h.close();

// Return the benchmark results:
resolve(results);
}
}

return new Promise(executor);
}
Insert cell
// creates a table representation of the benchmark results
function benchTable(...args) {
const $view = html`<progress style="margin-right:.5em;width:5em"></progress><output style="font:13px var(--sans-serif)">Running benchmark...</output>`;
bench(...args).then(results => {
const table = md`
## ${args[0]}

<table style="max-width: 100%">
<thead>
<tr>
<th style="text-align:left">Ok</th>
<th style="text-align:right">Iterations</th>
<th style="text-align:right">Elapsed</th>
<th style="text-align:right">Rate</th>
<th style="text-align:right">Benchmark</th>
</tr>
</thead>
<tbody>
${results.filter(
r => r.type === 'result'
).map(
e =>
html`<tr>
<td>${e.ok}</td>
<td style="text-align:right; font-variant-numeric: tabular-nums">${commas(
e.iterations
)}</td>
<td style="text-align:right; font-variant-numeric: tabular-nums">${fmt(
e.elapsed
)} ms</td>
<td style="text-align:right; font-variant-numeric: tabular-nums">${fmt(
e.rate
)} ops/s</td>
<td style="text-align:right; font-variant-numeric: tabular-nums">${
e.benchmark
}</td>
</tr>`
)}
</tbody>
</table>
`;
$view.replaceWith(table);
});

return $view;
}
Insert cell
stdlib = require("@stdlib/dist-flat")
Insert cell
fmt = d3.format(',.2f')
Insert cell
commas = d3.format(',d')
Insert cell
d3 = require('d3')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more