Last active
February 8, 2022 23:52
-
-
Save 7ombie/d6953a1ab933b9b15aa26ef2bdac2335 to your computer and use it in GitHub Desktop.
Simple script for testing the mean roundtrip time when pinging a worker thread (`postMessage`).
This file contains 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
worker.onmessage = function() { | |
/* This handler responds to each message from the worker thread | |
by storing the total roundtrip time in milliseconds, continuing | |
to iterate until the `deltas` array is full. At that point, the | |
function computes the mean average time (ignoring the first two | |
samples, as the first is invalid (and will always be zero), and | |
the second (the first genuine sample) will always take about an | |
order of magnitude longer than normal). The handler finishes by | |
logging the mean, then the array of times, before returning and | |
completing the test. | |
Note: This function uses a bunch of module-level globals, which | |
are defined immediately below the function. | |
Note: The current iteration (`i`, a `Number`) is sent (and then | |
immediately sent back) as the payload for the messages. | |
Note: On a first-gen M1 MBA 13, the mean is roughly 0.033ms. */ | |
const now = performance.now(); | |
deltas[i] = now - t; | |
t = now; | |
if (++i < deltas.length) return worker.postMessage(i); | |
const goodies = deltas.slice(2); | |
const overall = Array.from(goodies).reduce((x, y) => x + y, 0); | |
const average = overall / goodies.length; | |
console.log("roundtrip average:", average); | |
console.log("individual trips:", deltas); | |
}; | |
// initialize the variables that track the current iteration and time | |
let [i, t] = [0, performance.now()]; | |
// initialize the float array that accumulates the results, and create | |
// the worker (using a source string, a blob and an object url) | |
const trials = 1000; | |
const deltas = new Float64Array(trials + 2); | |
const script = "self.onmessage = e => self.postMessage(e.data)"; | |
const source = new Blob([script], {type: "text/javascript"}); | |
const worker = new Worker(URL.createObjectURL(source)); | |
// ping... | |
worker.onmessage(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment