[JST] Parallelism comparison
HTML
<h3>Compare WebWorker and setTimeout-based parallelism</h3>
<table cellpadding="5" border="1">
<tr>
<td></td>
<td>Value</td>
<td>Time</td>
</tr>
<tr>
<td>WebWorker</td>
<td id=webWorkerValue></td>
<td id=webWorkerTime></td>
</tr>
<tr>
<td>setTimeout</td>
<td id=setTimeoutValue></td>
<td id=setTimeoutTime></td>
</tr>
</table>
<button id=compareButton>Compare</button>
CSS
td {
width: 150px;
}
button {
margin-top: 20px;
}
JavaScript
// Some magic to run function as WebWorker
compareButton.onclick = function() {
webWorkerValue.innerHTML = "";
webWorkerTime.innerHTML = "";
setTimeoutValue.innerHTML = "";
setTimeoutTime.innerHTML = "";
var workerMessage = {
iterationCount: 400000000,
splitInterval: 2000000
};
calculatePiUsingWebWorker(workerMessage);
calculatePiUsingSetTimeout(workerMessage);
};
function calculatePiUsingWebWorker(workerMessage) {
var workerBlob = new Blob(["(" + workerImplementation.toString() + ")()"], {
type: 'text/javascript'
});
var workerInstance = new Worker(URL.createObjectURL(workerBlob));
workerInstance.onmessage = createMessageHandler(webWorkerValue, webWorkerTime);
workerInstance.postMessage(workerMessage);
}
function calculatePiUsingSetTimeout(workerMessage) {
var workerInstance = new workerImplementation(true);
workerInstance.postMessage = function(data) {
createMessageHandler(setTimeoutValue, setTimeoutTime)({ data: data });
};
workerInstance.onmessage({ data: workerMessage });
}
function workerImplementation(isSetTimeoutCase) {
var response = {},
self = this,
iterationCount, splitInterval;
this.onmessage = function(e) {
iterationCount = e.data.iterationCount;
splitInterval = e.data.splitInterval;
function calculatePi(pi, startN, iterationCount, splitInterval) {
for (var n = startN; n < iterationCount; n += 4) {
pi = pi + (4 / n) - (4 / (n + 2));
if (n > startN + splitInterval) {
if (isSetTimeoutCase) {
setTimeout(function() {
calculatePi(pi, n + 4, iterationCount, splitInterval);
});
} else {
calculatePi(pi, n + 4, iterationCount, splitInterval);
}
return;
}
}
response.end = performance.now();
response.pi = pi
self.postMessage(response);
}
response.start = performance.now();
calculatePi(0, 1, iterationCount, splitInterval);
...