speci/speci.js
2023-09-04 10:14:07 -07:00

94 lines
2 KiB
JavaScript

function doit() {
function make_x_first(x,y) {
return {x, y};
}
function make_y_first(x, y) {
return {y, x};
}
function make_mixed(x, y) {
if (Math.random() > 0.5) {
return make_y_first(x, y);
} else {
return make_x_first(x, y);
}
}
function make_randomized(x, y) {
let rando = (Math.random() * (2 ** 32 - 1)) | 0;
//let buckets = 256;
//random = rando % buckets;
let r = 'random' + rando;
let o = {[r]: r};
if (Math.random() > 0.5) {
o.y = y;
o.x = x;
} else {
o.x = x;
o.y = y;
}
return o;
}
const million = 1000 * 1000;
const n = 1 * million;
const runs = 100 * n;
function bulk(filler) {
let a = [];
for (let i = 0; i < n; i++) {
a.push(filler(i, i * i));
}
return a;
}
const x_first = bulk(make_x_first);
const y_first = bulk(make_y_first);
const mixed = bulk(make_mixed);
const randomized = bulk(make_randomized);
function time(func) {
const start = Date.now();
func();
const delta = Date.now() - start;
return delta;
}
function report(func) {
let delta = time(func);
console.log(`${delta} ms`);
}
function demo(dataSet) {
for (let i = 0; i < 3; i++) {
console.log(`run ${i+1}`);
report(() => {
let sumX = 0, sumY = 0;
for (let i = 0; i < runs; i++) {
let item = dataSet[i % dataSet.length];
sumX += item.x;
sumY += item.y;
}
return {x: sumX, y: sumY};
});
console.log(``);
}
}
console.log(`** x_first`);
demo(x_first);
console.log(`** y_first`);
demo(y_first);
console.log(`** mixed`);
demo(mixed);
console.log(`** randomized`);
demo(randomized);
}
doit();