Created
May 18, 2017 06:48
-
-
Save mbebenita/cfabc7e37b9f5a370205057e82acd9eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<script> | |
function sum(array) { | |
var num = 0; | |
for (var i = 0, l = array.length; i < l; i++) num += array[i]; | |
return num; | |
} | |
function mean(array) { | |
return sum(array) / array.length; | |
} | |
function variance(array) { | |
var m = mean(array); | |
return mean(array.map(function (num) { | |
return Math.pow(num - m, 2); | |
})); | |
} | |
function standardDeviation(array) { | |
return Math.sqrt(variance(array)); | |
} | |
window.onload = function () { | |
run(20); | |
} | |
let sab = new SharedArrayBuffer(4); | |
let arr = new Uint32Array(sab); | |
function measureTicksPerMs(c) { | |
let s = performance.now(); | |
let a = arr; | |
for (let i = 0; i < c; i++) { | |
a[0]++; | |
} | |
a[0] = 0; | |
return c / (performance.now() - s) | 0; | |
} | |
function createWorker() { | |
var code = ` | |
addEventListener("message", function (message) { | |
let arr = new Uint32Array(message.data); | |
while (true) { | |
arr[0] ++; | |
} | |
}); | |
`; | |
var blob = new Blob([code], {type: "application/javascript"}); | |
return new Worker(URL.createObjectURL(blob)); | |
} | |
function run(k) { | |
var worker = createWorker(); | |
worker.postMessage(sab); | |
let ticksPerMs = measureTicksPerMs(10000000); | |
function now() { | |
return arr[0] / ticksPerMs; | |
} | |
// Something to do that takes a while. | |
function gcd(a, b) { | |
if (!b) { | |
return a; | |
} | |
return gcd(b, a % b); | |
} | |
let i = 0; | |
let A = []; | |
let B = []; | |
function run() { | |
setInterval(() => { | |
// Should I recompute this periodically? | |
// ticksPerMs = measureTicksPerMs(10000000); | |
let s0 = performance.now(); | |
let s1 = now(); | |
for (let j = 0; j < 100000; j++) { | |
i += gcd(j++, 1234); | |
} | |
let e1 = (now() - s1); | |
let e0 = (performance.now() - s0); | |
A.push(e0); | |
B.push(e1); | |
console.log(""); | |
console.log(" ticksPerMs: " + ticksPerMs); | |
console.log(" performance.now: " + e0); | |
console.log(" sab.now: " + e1); | |
console.log("performance.now std: " + standardDeviation(A)); | |
console.log(" sab.now std: " + standardDeviation(B)); | |
}, 1000); | |
} | |
setTimeout(run, 100); // Wait a little while for the worker thread to start. | |
} | |
</script> | |
Open up the console. I'm trying to see if I can build a more accurate timer using SABs. | |
At the moment I'm getting a larger std for the SAB case. | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment