Compare Math.random() to Xoshiro64 (v2)

Revision 2 of this benchmark created on


Description

Note: extra HTML (and code) is to prevent "dead code elimination" and encourage realistic optimization from the JavaScript VM.

Preparation HTML

<p id="acc"></p>

Setup

// Xoshiro64
var rotl32 = (x, k) => (x << k) | (x >>> (32 - k));
var s64 = [0x921e3fc0, 0x9d720779];
function next32() {
  let s0 = s64[0];
  let s1 = s64[1];
  const result = rotl32(s0 * 0x9E3779BB, 5) * 5;
  s1 ^= s0;
  s64[0] = rotl32(s0, 26) ^ s1 ^ (s1 << 9);
  s64[1] = rotl32(s1, 13);
  return result;
}
function next32_inline() {
  let s0 = s64[0];
  let s1 = s64[1];
  const x = s0 * 0x9E3779BB;
  const result = ((x << 5) | (x >>> 27)) * 5; // (32 - 5) === 27
  s1 ^= s0;
  s64[0] = ((s0 << 26) | (s0 >>> 6)) ^ s1 ^ (s1 << 9); // (32 - 26) === 6
  s64[1] = (s1 << 13) | (s1 >>> 19); // (32 - 13) === 19
  return result;
}

// other setup
var numLoop = 16384;
function update(a, b) {
	return (b - a) / 2.0;
}
function finish(acc) {
	let elem = document.getElementById("acc");
	elem.innerText = acc;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Math.random()
let acc = 0.0;
for (let i = 0; i < numLoop; i++) {
  let res = Math.random();
  acc += update(res, acc);
}
finish(acc);
ready
Xoshiro64
let acc = 0.0;
for (let i = 0; i < numLoop; i++) {
  let res = next32();
  acc += update(res, acc);
}
finish(acc);
ready
Xoshiro64 (inline rotl)
let acc = 0.0;
for (let i = 0; i < numLoop; i++) {
  let res = next32_inline();
  acc += update(res, acc);
}
finish(acc);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.